skip to Main Content

What is the issue with the following code I have in trying to define my own function to sort by?

let a = ['name', 'age'];
console.log(a);
a.sort((x,y)=>x-y); // whyoesn't this sort properly?
console.log(a);
a.sort();
console.log(a);

2

Answers


  1. Chosen as BEST ANSWER

    x-y returns NaN and isn'g good for string comparisons. Try doing something like:

    let a = ['name', 'age'];
    console.log(a);
    a.sort((x,y)=>x===y?0:x>y?1:-1); // whyoesn't this sort properly?
    console.log(a);
    a.sort();
    console.log(a);


  2. It doesn’t make sense to subtract strings; you get NaN unless both operands can be converted to a number. You can instead use String#localeCompare for the comparator.

    The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

    let a = ['name', 'age'];
    a.sort((x, y) => x.localeCompare(y));
    console.log(a);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search