Blog archives

Javascript and sorting

Sorting in Javascript using the Array.sort() function doesn’t work how i thought it did:

var foo = [3, 4, 5, 2, 1];
foo.sort(function(a,b) {
    return a < b;

In Firefox this gives the result you expect ([1,2,3,4,5]), but in Chrome and Safari, it doesn’t (and in IE too probably). When re-reading the spec at Mozilla’s dev site i discovered why:

If compareFunction(a, b) is less than 0, sort a to a lower index than b. (…) If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

So, the return value should not be true or false but -1 or 1. The example above should be written as:

foo.sort(function(a,b) {
    return a - b;

Add a comment