Historical archive
The Numeric Sorting Trap in JavaScript Array.sort()
Why JavaScript sorts array elements as strings by default and how a comparator produces the expected numeric order.
JavaScript arrays use the sort() method for sorting, and the method accepts an optional comparator.
var a = [-1, -2, -3, -4, -5];
a.sort();
console.log(a);
// [-1, -2, -3, -4, -5]
The result is not ascending numeric order. Supplying a comparator fixes it:
var a = [-1, -2, -3, -4, -5];
a.sort(function (a, b) {
return a - b;
});
console.log(a);
// [-5, -4, -3, -2, -1]
Without a comparator, JavaScript converts elements to strings and compares their character sequences. That causes surprising results for negative values and arrays such as [111, 1, 2].
var a = [111, 1, 2];
a.sort();
console.log(a);
// [1, 111, 2]
a.sort(function (a, b) {
return a - b;
});
console.log(a);
// [1, 2, 111]
Use (a, b) => a - b for ascending numeric order and (a, b) => b - a for descending numeric order.