I'm trying to use JavaScript's sort function on arrays of numbers and sometimes it doesn't do anything:
var a = [200,20].sort(); // [20,200]
var b = [200,21].sort(); // [200,21]
I'm trying to use JavaScript's sort function on arrays of numbers and sometimes it doesn't do anything:
var a = [200,20].sort(); // [20,200]
var b = [200,21].sort(); // [200,21]
Javascript sorts everything as strings (=alphabetically) by default. The string "200"
is less than the string "21"
. To sort as numbers you have to tell it so:
[200,21].sort(function(a,b) { return a-b })
Yep, this is the standard behaviour for "sort" because it perform "string" reordering. If you want to sort by number value you must pass a "compare" function to sort, like this:
[200,21].sort(function (a, b) {
return a-b;
})
// [21, 200]
The function must return 0 for identical value, n < 0 if a < b and n > 0 if a > b. For that reason, the difference is enough to provide sorting (assuming that you're not using huge numbers)