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);
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
x-y
returnsNaN
and isn'g good for string comparisons. Try doing something like:It doesn’t make sense to subtract strings; you get
NaN
unless both operands can be converted to a number. You can instead useString#localeCompare
for the comparator.