As part of my computer engineering course, I wrote algorithms to sort array in different programming languages like Fortran, Pascal and even in C. We all did in our college days. However, as part of job, did you ever have to write such a program? I think no, because all modern languages provide built in functionality to sort.
JavaScript is not different. It has the sort function, which we can use whenever we need to sort an array. In this blog post, we will examine how JavaScript sort can be used in different scenarios.
Sorting One Dimensional String Array
Sorting an array in JavaScript is kid's play, provided the array is a one dimensional string array. If not? well, even if it is not one dimensional string array, it is not that difficult.
Then, let's start with one dimensional string array. Sort method of the Array prototype is handy here. See the below code.
var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog"];
arr.sort();
console.log("Sorted array: " + arr);
// Sorted array: brown,dog,fox,jumps,lazy,over,quick,the
Sorting String Array in Descending Order
What if you want to compare in descending order? Unfortunately, there is no method to support in descending order sort, but no need to worry. The reverse method of array comes in handy here. Apparently, you can sort in ascending order and then reverse the array to do sort in descending order.
var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog"];
arr.sort();
arr.reverse();
console.log("Sorted array: " + arr);
// Sorted array: the,quick,over,lazy,jumps,fox,dog,brown
Sorting Case Insensitive
Again, sort is case sensitive. What if you want a case insensitive sort? Sort function accepts a compare function, which is of great help.
var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "Dog"];
arr.sort(function(s1, s2) {return s1.toLowerCase().localeCompare(s2.toLowerCase())});
console.log("Sorted array: " + arr);
// Sorted array: brown,Dog,fox,jumps,lazy,over,quick,the
Of course, you can use the shorter syntax for function declaration for brevity.
var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "Dog"];
arr.sort((s1, s2) => s1.toLowerCase().localeCompare(s2.toLowerCase()));
console.log("Sorted array: " + arr);
// Sorted array: brown,dog,fox,jumps,lazy,over,quick,the
That's all about string array sort.
Sorting Numerical Arrays
Now let's see how we can sort numerical arrays. The sorting numerical array is not straight forward as string array sorting because of one reason. The Sort function by default considers the member elements as strings. So, if we sort a numerical array, the string sort will be happening, which will not give us the expected result. For example, 100 comes before 25, because the string "1" is bigger than "2". Solution? The compare function discussed in previous example again saves us.
var arr = [12, 0, 6, 22, 45];
arr.sort((n1, n2) => n1 - n2);
console.log("Sorted array: " + arr);
// Sorted array: 0,6,12,22,45
want it in descending order? Just change the second line.
arr.sort((n1, n2) => n2 - n1);
//Sorted array: 45,22,12,6,0
Sorting Array of Objects
Let's wind up by discussing the last point. Sorting an array of objects.
var arr = [{productId: 1000, productCode: 724123, productName: "Moto G5s Plus"},
{productId: 1001, productCode: 223426, productName: "Samsung On5"},
{productId: 1002, productCode: 523426, productName: "Apple iPhone 7 Plus"}];
arr.sort((item1, item2) => item1.productCode - item2.productCode);
console.log(JSON.stringify(arr));
// result:
// [{"productId":1001,"productCode":223426,"productName":"Samsung On5"},
// {"productId":1002,"productCode":523426,"productName":"Apple iPhone 7 Plus"},
// {"productId":1000,"productCode":724123,"productName":"Moto G5s Plus"}]
Probably, you should have got this, how to sort on a string key? For example, by productName in previous example? Yes, we can use the same method we used for case insensitive sort.
var arr = [{productId: 1000, productCode: 724123, productName: "Moto G5s Plus"},
{productId: 1001, productCode: 223426, productName: "Samsung On5"},
{productId: 1002, productCode: 523426, productName: "Apple iPhone 7 Plus"}];
arr.sort((item1, item2) => item1.productName.localeCompare(item2.productName));
console.log(JSON.stringify(arr));
// result:
// [{"productId":1002,"productCode":523426,"productName":"Apple iPhone 7 Plus"},
// {"productId":1000,"productCode":724123,"productName":"Moto G5s Plus"},
// {"productId":1001,"productCode":223426,"productName":"Samsung On5"}]