— JavaScript, Arrays, Sorting — 1 min read
Sorting arrays is a fundamental operation in JavaScript that allows you to arrange elements in a specific order. Whether you need to sort numbers, strings, or complex objects, JavaScript provides several built-in methods that simplify the sorting process. In this article, we'll cover some of the most commonly used sorting techniques and demonstrate how to implement them effectively.
To sort an array of numbers in JavaScript, you can use the sort()
method, which sorts elements based on their string representations by default. However, this may not give the expected results when dealing with numbers. To overcome this, you can provide a comparison function as an argument to the sort()
method.
1const numbers = [5, 1, 3, 2, 4];2numbers.sort((a, b) => a - b);3console.log(numbers); // Output: [1, 2, 3, 4, 5]
In the example above, we pass a comparison function (a, b) => a - b
to sort()
, which subtracts one number from another. This approach ensures that the numbers are sorted in ascending order.
For descending order, you can simply reverse the comparison:
1numbers.sort((a, b) => b - a);2console.log(numbers); // Output: [5, 4, 3, 2, 1]
Sorting an array of strings is straightforward with the sort()
method. By default, it arranges elements in lexicographical order (i.e., based on Unicode values).
1const fruits = ["apple", "orange", "banana", "kiwi"];2fruits.sort();3console.log(fruits); // Output: ["apple", "banana", "kiwi", "orange"]
To sort strings in a case-insensitive manner, you can provide a comparison function that converts all elements to lowercase or uppercase before performing the sort.
1fruits.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));2console.log(fruits); // Output: ["apple", "banana", "kiwi", "orange"]
The localeCompare()
method compares two strings and returns a negative value if the first string comes before the second, a positive value if it comes after, or zero if they are equal.
In JavaScript, sorting arrays of objects requires a bit more attention. By default, the sort()
method will not work as expected because it compares object references, rather than their properties.
To overcome this, you can provide a custom comparison function that specifies the property to compare.
1const products = [2 { name: "Keyboard", price: 25 },3 { name: "Mouse", price: 15 },4 { name: "Monitor", price: 100 },5];6
7products.sort((a, b) => a.price - b.price);8console.log(products);9/*10Output:11[12 { name: "Mouse", price: 15 },13 { name: "Keyboard", price: 25 },14 { name: "Monitor", price: 100 }15]16*/
In the above example, we sort the array of products
based on the price
property in ascending order.