I have always successfully sorted my arrays like this (when I did not want the standard lexicographic ordering):
var arr = […] // some numbers or so
arr.sort
The sort function expects a function that expects two arguments a
and b
, and returns:
In order to sort numbers in ascending order return a - b
will produce the correct return values; for example:
a b ret
1 2 -1
3 2 1
2 2 0
On the other hand return a > b
produces the following return values:
a b ret implied
1 2 false 0
3 2 true 1
2 2 false 0
In the above example, the sort function is told that 1 and 2 are same (and placing 1 before 2 or 2 before 1 does not matter). This will produce incorrect result, for example (in Chrome 49):
console.log([5, 8, 7, 1, 2, 3, 4, 6, 9, 10, 11, 12, 13].sort(function(a, b) {
return a > b;
}));
// [4, 5, 3, 1, 2, 6, 7, 8, 9, 10, 11, 12, 13]