Ryan's Blog

Like Twitter, but longer

RSS

On JavaScript sorting

This has caused a bit of controversy today.

But that result is probably by design. JavaScript doesn’t necessarily know what type of object it’s dealing with in that array, so it simply calls toString() on it and then compares that.

So calling

[1,5,10].sort()

is the same as calling

[5, 10, 1].sort(function(a, b) {
    as = a.toString();
    bs = b.toString();
    if (as == bs)
        return 0;
    if (as > bs)
        return 1;
    if (as < bs)
        return -1;
});

when really you should call

[5, 10, 1].sort(function(a, b) {
    return (a < b) ? -1 : (a > b) ? 1 : 0;
});

And here’s the JSFiddle to prove it.