TIL how the
Array.prototype.sort() sorts by default, and how to pass a comparator function in to the sort method if a different sort order is desired.
What is going on???
Array.prototype.sort() default sorts by ascii value. My integers were being converted to strings and compared as such. In the case above, integers with a 1 as their first digit come first in ascii…then 2…then 3…
To do a proper integer sort, you need to pass a comparator function to the
Array.prototype.sort() method that dictates how sorting should be accomplished. The comparator takes 2 arguments
(a, b) which represents two adjacent elements in the array to be sorted.
- If 0 is returned from the comparator, nothing is done to the positions of ‘a’ and ‘b’ in the array
- If a value greater than 0 is returned, ‘b’ comes first positionally in the array relative to ‘a’
- If a value less than 0 is returned, ‘a’ comes first positionally in the array relative to ‘b’
A proper integer sort is achieved by the following:
The comparator function above returns values that comply to the 3 rules above, and will sort the integer values appropriately.
See the following reference from Mozilla on
Array.prototype.sort() for additional info.