Basic Understanding of Sort Method
sort() method, as its name suggests, sorts every element in an array.
By default, the elements are converted into strings and sorted in ascending order based on UTF-16 code unit values.
If the array contains various types of characters such as signs, numbers, and letters with different cases, the order would be like this; signs* > numbers > upper case letters > lower case letters.
Customizing Sort Order — CompareFunction
When sorting the array that only has numbers, how do you think the elements would be ordered?
Let’s take a look at what happened with the example below.
I believe it was not what you expected.
As described above, the
sort() method converts every element into a string, so it won’t sort them by numerical order.
compareFunction , you can customize sort order as you wish so that you can fix this issue.
By setting two arguments
b , and return a certain value, you can manipulate how to sort. In this example,
a represents the element which
sort() method compares with the next element while
b represents the next element which
a is compared with.
compareFunction has two types of forms.
When an array contains only numbers as the last example, the form can be like the following. It’s assumed that the array does not contain
NaN! Please remove them if they exist!
If it is not the case, the form can be like the following.
The second one acts differently according to its return value. (in the last example, it returns
compareFunction must have the return value or it causes an error.
compareFunction(a, b)returns less than 0, leave
compareFunction(a, b)returns 0, leave
bunchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAScript standard only started guaranteeing this behavior in 2019, thus, older browsers may not respect this.
compareFunction(a, b)returns greater than 0, sort
Let’s break down what’s happening here with the last example.
Comparing these two elements, the condition
a > bis true and returns
Nothing changes here.
["lettuce", "cabbege", "tomato", "cucumber", "onion", "squash"]
"tomato" . The function returns
1 this time, so
"tomato" comes before
["lettuce", "tomato", "cabbege", "cucumber", "onion", "squash"]
This time, comparing
b , it returns
1 again. The order changes like the following.
["tomato", "lettuce", "cabbege", "cucumber", "onion", "squash"]
Continuing these steps, each element gets compared, like a round-robin tournament, and changes order respectively.
In consequence, an array gets sorted as intended.
compareFunction , the
sort() method can work with an associative array, which means it sorts values accessing each with keys (properties).
The following example sorts the age of each Disneyland from the oldest to the youngest.
Last but not least, this method acts on the existing array unlike
If you need to keep an original array, declare a new variable and assign a copy of the original array using
slice() method. Then, sort the copy.