Sorting arrays is a fundamental operation in JavaScript used to organize data in a specific order. Whether sorting numbers, strings or custom objects, JavaScript’s sort()
method provides powerful functionality.
Understanding the sort()
Method
The sort() method sorts the elements of an array in place and returns the sorted array. By default, it converts elements to strings and sorts them in ascending order based on their Unicode values.
Syntax
array.sort(compareFunction);
- compareFunction (optional): A function that defines the sorting logic.
Default Behavior of sort()
When no compare function is provided, sort() arranges array elements as strings.
Example:
let fruits = ["Banana", "Apple", "Cherry"];
fruits.sort();
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
Sorting Numbers Without a Compare Function
Sorting numbers without a compare function leads to incorrect results because so
rt()
converts numbers to strings.
Example:
let numbers = [40, 100, 1, 5];
numbers.sort();
console.log(numbers); // Output: [1, 100, 40, 5]
Custom Sorting with compareFunction
To sort numbers correctly, you must provide a compare function.
Syntax of compareFunction:
function compare(a, b) {
return a - b;
}
- a – b: Sorts in ascending order.
- b – a: Sorts in descending order.
Examples
1. Sorting Numbers in Ascending Order
let numbers = [40, 100, 1, 5];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 5, 40, 100]
2. Sorting Numbers in Descending Order
let numbers = [40, 100, 1, 5];
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [100, 40, 5, 1]
3. Sorting Strings (Case-Sensitive)
By default, sort() is case-sensitive and places uppercase letters before lowercase ones.
let words = ["banana", "Apple", "cherry"];
words.sort();
console.log(words); // Output: ["Apple", "banana", "cherry"]
4. Sorting Strings in Case-Insensitive Order
let words = ["banana", "Apple", "cherry"];
words.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(words); // Output: ["Apple", "banana", "cherry"]
5. Sorting Objects Based on Properties
let products = [
{ name: "Laptop", price: 800 },
{ name: "Phone", price: 500 },
{ name: "Tablet", price: 300 },
];
// Sort by price in ascending order
products.sort((a, b) => a.price - b.price);
console.log(products);
/* Output:
[
{ name: "Tablet", price: 300 },
{ name: "Phone", price: 500 },
{ name: "Laptop", price: 800 }
]
*/
Sorting with localeCompare()
The localeCompare() method is ideal for string sorting, especially for non-English characters or locale-specific comparisons.
Example:
let cities = ["Paris", "new York", "Berlin"];
cities.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
console.log(cities); // Output: ["Berlin", "new York", "Paris"]
Reversing an Array
To sort an array in descending order without a compare function, use reverse() after sorting.
Example:
let fruits = ["Banana", "Apple", "Cherry"];
fruits.sort().reverse();
console.log(fruits); // Output: ["Cherry", "Banana", "Apple"]
Practical Use Cases
- Sorting User Data: Organize user records by age, name, or other properties.
- Dynamic Filtering: Arrange search results or product listings based on price, ratings or relevance.
- Locale-Sensitive Sorting: Handle multi-language applications.