Reputation: 2188
I have got a very strange result trying to sort an array:
[0,1,2,3,4,5,6,7,8,9,10].sort(function(a,b) {return a > b;})
Result:
[5, 0, 1, 2, 3, 4, 6, 7, 8, 9, 10]
I would like to understand, why is this result return? I know, that sort function should be written like this:
[0,1,2,3,4,5,6,7,8,9,10].sort(function(a,b) {return a - b;})
Upvotes: 1
Views: 115
Reputation: 386883
Yes you could get strange sorting results, for example in Chrome, where the sorting starts with the first and last element and goes on with the middle element.
Basicall you get the following protocoll
return needed a b a > b value value comment --- --- ------ ------ ------ ----------- 0 10 false 0 -1 wrong value 0 5 false 0 -1 wrong value 2 0 true 1 1 9 0 true 1 1 8 0 true 1 1 7 0 true 1 1 6 0 true 1 1 1 0 true 1 1 4 0 true 1 1 3 0 true 1 1 2 3 false 0 -1 wrong value 3 4 false 0 -1 wrong value 4 1 true 1 1 3 1 true 1 1 2 1 true 1 1 4 6 false 0 -1 wrong value 6 7 false 0 -1 wrong value 7 8 false 0 -1 wrong value 8 9 false 0 -1 wrong value 9 10 false 0 -1 wrong value
Basically you get a value for equal items, bu you have unequal items to compare.
You need a stable sort function which is kind of symetrical in the way as it yields the nevgative value with switched parameters.
sortFn(a, b) === -sortFn(b, a)
If you return only values of 0
and 1
, you miss -1
.
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sort(function(a, b) {
console.log(a, b, a > b);
return a > b;
}));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1