JavaScript sort()
sorting elements of an array (without and with comparison methods)
Motivation
Suppose we have an array and we wish to sort its elements...
We could use the built-in sort()
function to iterate and rearrange:
In the example above, sort()
, by default, sorts by
converting all values into strings
comparing each character's UTF-16 encoding values with the following order:
arrays
numbers, sorted by digit (i.e. 1, before 20, before 21, before 9)
strings beginning with uppercase letters
NaN
curiously is considered such a string
objects
the curly braces fall in between uppercase and lowercase letters!
strings beginning with lowercase letters
null
(but notundefined
) is considered such a string
undefined
empty slots
So, we can see here that sort()
by default is pretty screwed up:
Sorting numbers by number (not first digit)
To sort an array of numbers, we would need to pass a comparison function as a callback function when calling sort()
:
This callback function "(a,b) => a-b
" simply:
iterates through each pair of elements in the array
compares the two values and does its rearranging in place
it creates no new arrays
however, it changes the original array
Sorting numbers in descending order
Also:
(a,b) ⇒ ( a > b ? -1 : 0 )
sorts numbers in descending fashion
Caution
Remember that sort()
:
returns an array that by default sorts by UTF-16 encodings
does modify the original array
can take a comparison callback function as a parameter
(a,b) ⇒ a - b
sorts in ascending order
(a,b) ⇒ ( a > b ? -1 : 0 )
sorts in descending order
Last updated