Sorting is a process of arranging items or data properly In programming, sorting is arranging a collection of data in an order. Sorting is a useful operation in programming, it helps to organize the data that makes it easy to understand, search, retrieve and analyse it, but question is How to Sort an Array in JavaScript?
In JavaScript, there is a built-in method called ‘Array.sort()’ method that allows programmers for sorting arrays.
A Step-By-Step guide on How to Sort an Array in JavaScript
Why Sorting Arrays is Useful in JavaScript?
Firstly, let’s understand why sorting arrays is useful while programming in JavaScript. We use sorting because it helps to convert the data systematically, which makes the data as easy to understand and work with it.
For example, we have an array of student names in a class:
let names = [“Mike”, “Toto”, “Bob”, “Lee”];
If we sort this array of name alphabetically, it can be easy to present the information of student names in a structured way.
JavaScript has a built-in ‘sort()’ method for sorting arrays. Let’s see how to use ‘sort()’ method with basic JavaScript programs.
Sorting elements of an array in Alphabetical Order
When sort() method is called without arguments, it sorts the elements of the arrays in alphabetical order.
Let’s take the above example of student names:
let names = ["Mike", "Toto", "Bob", "Lee"]; names.sort(); console.log(names); output: ['Bob', 'Lee', 'Mike', 'Toto']
Sorting elements of an array in Reverse Alphabetical Order
Now, it is also important to know how to sort the elements of the array in reverse alphabetical order. What is reverse alphabetical order? It simply means arranging the elements from ‘Z’ to ‘A’. Note that for reverse alphabetical order, we need to provide a custom comparison function to the ‘sort()’ method.
Let’s take the above example again.
let names = ["Mike", "Toto", "Bob", "Lee"]; names.sort((a, b) => b.localeCompare(a)); console.log(names); output: ['Toto', 'Mike', 'Lee', 'Bob']
Here is a question for you:
What will be the output of the following code?
let a = [4, 33, 1111, 22]; a.sort(); Answer: a = [1111, 22, 33, 4];
The ‘sort()’ method converted the array elements to string temporarily like this: [‘1111’, ‘22’, ‘33’, ‘4’]. Then the ‘sort()’ method compare the string representations of these elements alphabetically(lexicographically). While comparing, the string ‘1111’ comes before ‘22’ because ‘1’ comes before ‘2’ in the Unicode character set. Same for ‘22’ and ‘33’ and ‘4’ comes in the last.
If you want to sort them as numerical value, you have to put custom comparison function to the ‘sort()’ method.
Now let’s see how we sort the array elements as numbers:
Numerical Sorting in Arrays
Sorting Number elements of an array in Ascending Order
To sort an array of number elements in ascending order, we have to provide a comparison function tot the ‘sort()’ method.
let nums = [4, 33, 1111, 22]; nums.sort((a,b) => a - b); console.log(nums); // output // [4, 22, 33, 1111]
Let me explain in detail, here we are providing a comparison function. Notice the ‘a -b’ where ‘a’ is representing first element and ‘b’ is second element. ‘a -b’ calculates the difference between the two elements. If ‘a – b’ return negative value, it means ‘a’ should come before ‘b’ in the sorted order. If ‘a – b’ returns zero, then both ‘a’ and ‘b’ will be considered as equal in sorted order. And if ‘a – b’ return positive value, it means the ‘b’ will come before ‘a’ in the sorted order.
This is our example:
let nums = [4, 33, 1111, 22]; nums.sort((a,b) => a - b);
Let’s break down the process in stepwise to get better understanding:
- The sort() method starts by comparing the first two elements ‘4’ and ‘33’. As defined, ‘a -b’. The result of ‘4 – 33’ is ‘-29’ which is a negative value, so the ‘a’ which is ‘4’ will come before ‘b’ which is ‘33’.
- Next the sort() method will take ‘33’ as ‘a’ and ‘111’ as ‘b’, now the result ‘a-b’ which is ’33-111’ will generate ‘-1078’ negative value, it means ‘a’ which is ‘33’ will come before ‘b’ which is ‘1111’.
- Then, sort() method will take ‘1111’ as ‘a’ and ‘22’ as ‘b’, now the result ‘a-b’ which is ‘1111-22’ returns ‘1089’. This time it is a positive value. As we know ‘b’ will come before ‘a’, so ‘22’ will come before ‘1111’ in array.
- Lastly, it compares ‘4’ and ‘22’, it will return a negative value of ‘-18’. Negative value comes before the positive, so 4 will come before ‘22’.
The result of this sorting will be:
[4, 22, 33, 1111]
The elements of the array are sorted in ascending order.
Sorting Number elements of an array in Descending Order
Now let’s see how we can sort the number elements of an array in descending order. Same as ascending order, we have to provide a custom comparison function in ‘sort()’ method with little tweak. Here is how to achieve this:
let nums = [4, 33, 1111, 22]; nums.sort((a,b) => b - a);
This time a will be subtracted from ‘b’. If the result is positive, ‘b’ will come before ‘a’ in the array.
The code will return arrays with elements in descending order:
[1111, 33, 22, 4]
Custom Sorting
Sorting by Date in JavaScript
Now we will see how to sort an array in JavaScript by date. Let’s suppose we have an array of dates elements, and we want to sort the dates elements in ascending order.
const dates = ["2018-08-17", "2021-02-06", "2023-05-22", "2024-05-15"];
To sort the date elements of dates array in ascending order we will use Date() object with comparison function.
The complete code is below:
const dates = ["2018-08-17", "2021-02-06", "2023-05-22", "2024-05-15"]; dates.sort((a, b) => new Date(a) - new Date(b)); // Resulting sorted array console.log(dates); // output // [ '2018-08-17', '2021-02-06', '2023-05-22', '2024-05-15' ]
- The new Date() is a constructor in JavaScript which creates a new Date object.
Sorting Array of objects by a particular key
Now, another query we have is how to sort an object array by a key in JavaScript.
Let’s take an example of profile array of objects.
const profiles = [ { name: "Sohit", age: 32, city: "Delhi" }, { name: "Manoj", age: 45, city: "Mumbai" }, { name: "Rakhi", age: 38, city: "Nagpur" } ];
Now, we have to sort this array of object by ‘age’ property in ascending order.
We can achieve this by: profiles.sort((a, b) => a.age - b.age); The output will be: [ { name: "Sohit", age: 32, city: "Delhi" }, { name: "Rakhi", age: 38, city: "Nagpur" }, { name: "Manoj", age: 45, city: "Mumbai" } ]
Conclusion:
In this blog post, we have covered some topics of sorting arrays in JavaScript using different methods and techniques.