Does Array.prototype.sort (compareFn) work differently in browsers?

I tested the comparison function specified as a callback Array.prototype.sort(compareFn)when compareFn returns value = 0, but I get unexpected behavior in Chrome:

/* Chrome */
[1,2,3,4,5,6,7,8,9,10].sort(function(){return 0;});
//returns [1,2,3,4,5,6,7,8,9,10]
[1,2,3,4,5,6,7,8,9,10,11].sort(function(){return 0;})
//WUT? returns [6, 1, 3, 4, 5, 2, 7, 8, 9, 10, 11]

/* Firefox */
[1,2,3,4,5,6,7,8,9,10].sort(function(){return 0;});
//returns [1,2,3,4,5,6,7,8,9,10]
[1,2,3,4,5,6,7,8,9,10,11].sort(function(){return 0;});
//Work fine: returns [1,2,3,4,5,6,7,8,9,10,11]

Does anyone know what happened?

+4
source share
1 answer

I get unexpected behavior in Chrome. Does anyone know what is going on?

Actually, this is not unexpected. It looks like your version of Firefox browser implements stable sorting, while your version of Chrome browser does not. The browser does not need to use a robust sorting algorithm (and can choose performance by stability).

, , .

, 11 . 9 (45 ), (39 ) (52 ). () , 9 , () .

console.log([
    {name: 'John', age: 45},
    {name: 'Pete', age: 45},
    {name: 'Matt', age: 45},
    {name: 'Liam', age: 52},
    {name: 'Jack', age: 45},
    {name: 'Will', age: 45},
    {name: 'Zach', age: 45},
    {name: 'Josh', age: 45},
    {name: 'Ryan', age: 45},
    {name: 'Mike', age: 39},
    {name: 'Luke', age: 45}
  ].sort(function(a, b){
    // sort by ascending age
    return a.age - b.age;
  }).map(function(i){
    // get a sorted list of names
    return i.name;
  }).join(', ')
);

Chrome,

Mike, Will, Matt, John, Jack, Pete, Zach, Josh, Ryan, Luke, Liam

.

Mike, John, Pete, Matt, Jack, Will, Zach, Josh, Ryan, Luke, Liam

, , , :

39, 45, 45, 45, 45, 45, 45, 45, 45, 45, 52

, ( 0 ). ( Chrome, 11 ), ( Firefox).

Chrome 10 (, , ) 11 . , Chrome Insertion () (< = 10 ) Quicksort () .

, , , SO .

+3

Source: https://habr.com/ru/post/1677490/


All Articles