- Sorting an array of strings
- Sorting an array of numbers
- Sorting an array of objects by a specified property
sort() method to sort arrays of numbers, string, and objects.
sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the
sort() method changes the positions of the elements in the original array.
By default, the
sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
sort() method casts elements to strings and compares the strings to determine the orders.
Consider the following example:
The output is:
In this example, the
sort() method places 10 before 2 because the string “10” comes before “2” when doing a string comparison.
To fix this, you need to pass a compare function to the
sort() method. The
sort() method will use the compare function to determine the orders of elements.
The following illustrates the syntax of the
sort() method accepts an optional argument which is a function that compares two elements of the array.
If you omit the compare function, the
sort() method sorts the elements with the sort order based on the Unicode code point values of elements as mentioned earlier.
The compare function of the
sort() method accepts two arguments and returns a value that determines the sort order. The following illustrates the syntax of the compare function:
compare() function accepts two arguments
sort() method will sort elements based on the return value of the
compare() function with the following rules:
compare(a,b)is less than zero, the
ato a lower index than
b. In other words,
awill come first.
compare(a,b)is greater than zero, the
bto a lower index than
a, i.e., b will come first.
compare(a,b)returns zero, the
sort()method considers a equals b and leaves their positions unchanged.
To fix the issue of sorting the number, you can use the following syntax:
Or you can define the comparison function using the arrow function syntax:
And the following is the simplest since the elements of the array are numbers:
Sorting an array of strings
Suppose you have an array of string named
animals as follows:
To sort the elements of the
animals array in ascending order alphabetically, you use the
sort() method without passing the compare function as shown in the following example:
To sort the
animals array in descending order, you need to change the logic of the compare function and pass it to the
sort() method as the following example.
Suppose you have an array that contains elements in both uppercase and lowercase as follows:
To sort this array alphabetically, you need to use a custom compare function to convert all elements to the same case e.g., uppercase for comparison and pass that function to the
Sorting an array of strings with non-ASCII characters
sort() method is working fine with the strings with ASCII characters. However, for the strings with non-ASCII characters e.g., é, è, etc., the
sort() method will not work correctly. For example:
As you see, the
écureuil string should come before the
To resolve this, you use the
localeCompare() method of the
String object to compare strings in a specific locale, like this:
The elements of the
animaux array now are in the correct order.
Sorting an array of numbers
Suppose you have an array of numbers named
scores as in the following example.
To sort an array of numbers numerically, you need to pass into a custom comparison function that compares two numbers.
The following example sorts the
scores array numerically in ascending order.
To sort an array of numbers numerically in descending order, you just need to reverse the logic in the compare function as shown in the following example:
Sorting an array of objects by a specified property
The following is an array of
employee objects, where each object contains three properties:
Sorting objects by a numeric property
The following example shows how to sort the employees by
salary in ascending order.
This example is similar to the example of sorting an array of numbers in ascending order. The difference is that it compares the
salary property of two objects instead.
Sorting objects by a string property
To sort the
employees array by
name property case-insensitively, you pass the compare function that compares two strings case-insensitively as follows:
Sorting objects by the date property
Suppose, you wish to sort employees based on each employee’s hire date.
The hire date data is stored in the
hireDate property of the employee object. However, it is just a string that represents a valid date, not the
Therefore, to sort employees by hire date, you first have to create a valid
Date object from the date string, and then compare two dates, which is the same as comparing two numbers.
Here is the solution:
In fact, the
sort() method calls the compare function multiple times for each element in the array.
See the following example:
How it works:
- First, declare an array
riversthat consists of the famous river names.
- Second, sort the
riversarray by the length of its element using the
sort()method. We output the elements of the
riversarray to the web console whenever the
sort()method invokes the comparison function .
As shown in the output above, each element has been evaluated multiple times e.g., Amazon 4 times, Congo 2 times, etc.
If the number of array elements is increasing, it will potentially decrease the performance.
You cannot reduce the number of times that comparison function is executed. However, you can reduce the work that the comparison has to do. This technique is called Schwartzian Transform.
To implement this, you follow these steps:
- First, extract the actual values into a temporary array using the map() method.
- Second, sort the temporary array with the elements that are already evaluated (or transformed).
- Third, walk the temporary array to get an array with the right order.
Here is the solution:
sort() method to sort arrays of strings, numbers, dates, and objects.