Why can't JavaScript sort [5, 10, 1]?
javascript, sorting
Solution
Javascript sorts alphabetically. This means that "10" is lower than "5", because "1" is lower than "5".
To sort numerical values you need to pass in numerical comparator like this:
function sorter(a, b) {
if (a < b) return -1; // any negative number works
if (a > b) return 1; // any positive number works
return 0; // equal values MUST yield zero
}
[1,10, 5].sort(sorter);
Or you can cheat by passing simpler function:
function sorter(a, b){
return a - b;
}
[1, 10, 5].sort(sorter);
Logic behind this shorter function is that comparator must return `x>0 if a > b`, `x<0 if a < b` and `zero if a is equal to b`. So in case you have
a=1 b=5
a-b will yield negative(-4) number meaning b is larger than a
a=5 b=1
a-b will yield positive number(4) meaning a is larger than b
a=3 b=3
a-b will yield 0 meaning they are equal
Problem
This seems like a simple sort, yet JavaScript is giving an incorrect result. Am I doing something wrong or is this a language quirk? [5, 10, 1].sort(); [ 1, 10, 5 ]