-2

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);
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

4

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);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
-1

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);
David542
  • 104,438
  • 178
  • 489
  • 842