Reputation: 363
I noticed IE9 sort order is changing elements order when comparison function returns 0
.
See:
var myarray=[
{id:1,val:0},
{id:2,val:0},
{id:3,val:7},
{id:4,val:41}
];
myarray.sort(function(a,b){return a.val - b.val});
for(var i in myarray)
{
console.log(myarray[i].id);
}
Current stable versions of Chrome, Firefox, Opera and Safari got the following output: 1 2 3 4
.
Same output for IE7 and IE8.
IE9 output is: 2 1 3 4
Why? Is that normal?
Upvotes: 1
Views: 1904
Reputation: 324627
Don't use for...in
on an array if you're trying to iterate over the numeric properties, for two reasons:
Array.prototype
showing up;Both points also apply to Object
s. Chrome in fact does not conform to the most common browser behaviour, leading to heated debate in a Chrome bug report.
Upvotes: 4
Reputation: 44078
From MDC (emphasis mine):
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. [Note: the ECMAscript standard does not guarantee this behaviour], and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
In my experience, only Chrome/Firefox get this right. Opera 11's behavior for me is .. not well defined.
E.g., using sort to move all zeroes to the top of the array:
[1, 0, 3, 0, 5, 0, 2].sort(function (a, b) { return b === 0 && 1 || 0;});
Upvotes: 3
Reputation: 245459
Based on your sort function, both of those elements are equal and it shouldn't matter which order they appear in. It is up to the browser to either leave the order as it is or switch the order as it sees appropriate...neither is a guarantee.
If the two aren't equal, then your sort function is incorrect and should take the other items into account as well.
Upvotes: 2