Understanding Javascript .sort Parameter
Solution 1:
.sort
takes an optional parameter, which should be a function.
.sort
then calls that function repeatedly, passing it a pair of values from the array (the a
and b
parameters). The function then returns a value which is interpreted like so:
- If the returned value is less than 0, then
a < b
- If the returned value is greater than 0, then
a > b
- If the returned value is exactly 0, then
a == b
Using this, .sort
figures out the order of the items using whatever sorting algorithm the browser has been programmed to use.
In the absence of a sorting function, .sort
will sort the items as strings - this is just an arbitrary point of the design. Ideally you should be passing a function to be used whenever you want to .sort
things, as is the case here where the function forces the values to be compared as numbers.
Solution 2:
For whatever reason (and I should find documentation) the default behavior for Array.prototype.sort
is to sort by string, not numerically. That means that you have to define numeric sorting behavior.
How do
a
andb
get populated - Welcome to the world of functional programming. The array is iterated over internally and the callback function is called with a (first element) and b (second element) until the elements are exhausted. You don't have to worry too much about this, just know that that is what happens.The documentation on this is pretty clear, fortunately. If the return value of the callback is less than 0,
a
has a lower index thanb
. If0
is returned, keep them at the same index relative to other elements. If a positive value is returned,b
has a lower index thana
. That means thata - b
is guaranteed to work properly for numerical sorting. However, you will run into trouble with this callback function if there are any non-numeric elements. Only use it if you know for a fact that the array contains only numeric elements.This does a simple insertion sort and actually does not go two at a time, but will backtrack if
b
happens to be less thana
. You can examine this behavior by adding aconsole.log(a,b)
to the sort callback method.
Solution 3:
The JavaScript .sort()
function always sorts arrays as if their contents were strings, by default. That's just what it does. It's basically that the default sort function does a .toString()
on each value.
Here's a link to the specification. It's very confusing, but the key is towards the end of the description of the sorting comparison process.
Post a Comment for "Understanding Javascript .sort Parameter"