Sorting arrays effectively
This article shows you how to sort arrays in JavaScript with the sort() method
Arrays are a powerful tool that allows us to group related data under a single data type. One can do many things with arrays but sometimes it's better to have the array in order first. The good thing JavaScript has a method that allows us to sort an array easily.
sort() method
The sort() method allows us to sort an array and returns the sorted array. By default, the sort() method sorts elements in an array alphabetically or in ascending order with the smallest value first and largest value last.
Let's try out this code snippet.
let names = ["Travis", "Kelly", "Jordan", "Michael"];
names.sort();
console.log(names);
As we expected, the array is sorted alphabetically. The output is:
["Jordan", "Kelly", "Michael", "Travis"]
When performing a numerical sort, by default the sort() method casts elements into strings and compares the strings to determine the orders.
Consider the following example:
let times = [0, 1, 2, 3, 10, 20, 30];
times.sort();
console.log(times);
The output is:
[0, 1, 10, 2, 20, 3, 30];
In this example, the sort() method places 10 before 2 because the string "10" comes before "2" when doing a string comparison. This works well for strings because "Jordan" comes before "Kelly". However, if numbers are sorted as strings, "2" is bigger than "10" because "2" is bigger than "1". Because of this, the sort() method will produce incorrect results when sorting numbers. 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 order of elements.
The following illustrates the syntax of the sort() method with the compare function.
array.sort(comparefunction)
The sort method accepts an optional argument which is a function that compares two elements of the array. The compare function of the sort() method accepts two arguments and returns a value that determines their order. The sort() method will sort elements based on the return value of the compare() function with the following rules:
- If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other words, if the result is negative, a will come first.
- If compare(a,b) is greater than zero, the sort() method sorts b to a lower index than a. In other words, if the result is positive, b will come first.
- If compare(a,b) returns zero, the sort() method considers a to be equal to b and leaves their positions unchanged.
Example:
let marks = [40, 100, 10, 25, 85, 58, 60];
marks.sort(function(a, b){return a - b});
console.log(marks);
The output is:
[10, 25, 40, 58, 60, 85, 100]
The compare function compares all the values in the array, two values at a time (a, b).
When comparing 40 and 100, the sort() method calls the compare function (40, 100).
The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort function will sort 40 as a lower value than 100.
Use the same trick to sort an array in descending order.
let marks = [40, 100, 10, 25, 85, 58, 60];
marks.sort(function(a, b){return b - a});
console.log(marks);
The output is:
[100, 85, 60, 58, 40, 25, 10]
Sorting an array of objects by a specified property.
Even if objects have properties of different data types, the sort() method can be used to sort the array. The solution is to write a compare function to compare the property values.
The following is an array of employee objects, where each object contains three properties: name, salary, and hireDate.
let employees = [
{name: 'John', salary: 90000, hireDate: "July 1, 2010"},
{name: 'David', salary: 75000, hireDate: "August 15, 2009"},
{name: 'Ana', salary: 80000, hireDate: "December 12, 2011"}
];
Sorting objects by a numeric property
In this example, we shall sort employees by salary in ascending order.
// sort by salary
employees.sort(function (x, y) {
return x.salary - y.salary;
});
console.table(employees);
Try out the above code snippets and see the results. The example is similar to that 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
Comparing string properties is a little more complex. To sort the employees array by name property case-insensitively, you pass the compare function that compares two strings case-insensitively as follows:
employees.sort(function (x, y) {
let a = x.name.toUpperCase(),
b = y.name.toUpperCase();
if (a < b) {return -1;}
if (b > a) {return 1;}
return 0;
});
console.table(employees);
Sorting objects by the date property
What if 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's just a string that represents a valid date, not a Date object. To sort the employees by hire date, you have to first create a valid Date object from the date string, and then compare two dates, the same thing as comparing two numbers.
employees.sort(function (x, y) {
let a = new Date(x.hireDate),
b = new Date(y.hireDate);
return a - b;
});
console.table(employees);
Conclusion
In this tutorial, you have learned how to use the JavaScript Array sort() method to sort arrays of strings, numbers, objects, and dates.
Thanks for reading!!