Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript. Array .sort() method returns different results for Chrome and Firefox if array contains duplicate numbers

I have array containing random numbers. When I trying to sort this array via .sort() method, the result is different if array contains duplicate numbers. The code below works differently in Chrome and Firefox:

[1,2,3,4,5,6,7,8,9,2,15,3,4,5,1,2,3,4,0,2,3].sort(function(a, b) {
  console.log("a=", a, "b=", b)
})

Plunker: http://plnkr.co/edit/Ocm1ZSXgkoCM7FQeH0v5

Does it bug ? How to fix this behavior to have same result in Chrome and FF ?

like image 580
Sergio Ivanuzzo Avatar asked Jan 06 '23 02:01

Sergio Ivanuzzo


1 Answers

It works with a proper return value.

var array = [1,2,3,4,5,6,7,8,9,2,15,3,4,5,1,2,3,4,0,2,3];

array.sort(function(a, b) {
    return a - b;
});
console.log(array);

array.sort(function(a, b) {
    return (a & 1) - (b & 1) || a - b;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 180
Nina Scholz Avatar answered Jan 07 '23 14:01

Nina Scholz