On JavaScript sorting
This has caused a bit of controversy today.
[5, 10, 1].sort();
// [1, 10, 5]
This is why they laugh at you JavaScript, this.
— I Am Devloper (@iamdevloper) January 9, 2014
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.