In IE 9, if I type this in the console:
[1, 4, 2, 3].sort(function (a, b) { return a < b; });
The resulting array is: [1, 4, 2, 3]
.
If I do this in FF/Chrome, I get it, reverse-sorted: [4, 3, 2, 1]
.
How come this doesn't work in IE?
EDIT: Is there a function out there that abstracts these browser differences? In other words, is there a function I can pass function(a, b) { return a < b; } in and get the same result in all browsers? Any open-source stuff?
Maybe because the function is supposed to return
-1
ifa
is smaller,0
if they are equal, and1
ifa
is larger (or vice versa if you want reverse order). Edit: In fact, it must be zero, a positive or negative number (as @pimvdb pointed out, and that's what I make use of in the example below). Your function will never return-1
though and that might create problems.Consider
1
and3
. Your function returns1
for1 < 3
, which is ok, but returns0
for3 < 1
. In one case the number are different, in the other you are saying that they are equal.That FF/Chrome sort it in reverse order might be due to the sorting algorithm they are using.
Try:
Update: To substantiate this, we can have a look at the specification, Section 15.4.4.11 Array.prototype.sort(comparefn), where the properties are given which have to be fulfilled by a comparison function: