I was using the sort algorithm like this
top.sort(function(a,b){ return b > a});
I expected the array be ordered descending. It worked for top = [1,2,3,4,5,6,7,8,9,10]
But with top = [1,2,3,4,5,6,7,8,9,10,11]
I got an unexpected result like this
[6, 11, 10, 9, 8, 7, 5, 4, 3, 2, 1]
I have discovered that Ive used the sort function wrong. I should have used
top.sort(function(a,b){ return b - a});
Now whats the difference? Why does the top one not work like I expected (but works with a array length smaller than 11?
The sort function callback expects three possible return values:
less than 0
0
greater than 0
To tell it whether two values are the same or which is greater. Your single comparison was only returning true
or false
which would be cast to 1
or 0
which is not enough information to correctly evaluate which one is greater. It could work when b
was greater than a
, but would return false
(likely interpreted as 0
) when a
was greater than b
which would wrongly tell the sort algorithm that these two values are equal.
On the other hand,
return b - a
correctly provides all three return values for all possible numeric values of b
and a
and thus it works properly. If your values were not numbers, then you would have to more explicitly code a comparison that will return the three types of return values. Returning the results of the subtraction just happens to meet the sort callback criteria. It is certainly not the only way to code a comparison function.
In fact, if you want to sort an array of strings, you can use a different type of comparison that is also coded to return the three types of return values:
var result = ["hello", "goodbye", "adios"].sort(function(a, b) {
return a.localeCompare(b);
});
document.write(JSON.stringify(result));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With