Array.sort()
The Array.sort()
method in JavaScript is used to sort the elements of an array in place and return the sorted array. By default, the elements are converted to strings and sorted in ascending order based on their Unicode values.
Syntax
sort()
sort(compareFn)
Parameters
Parameter | Description |
---|---|
compareFn | (Optional) A function that defines the sort order. It takes two arguments and returns a number:
|
Return Value
The sort()
method returns the sorted array. The original array is modified in place.
Examples
1. Default Sorting
By default, the sort()
method sorts elements as strings in ascending order.
const fruits = ["banana", "apple", "cherry", "date"];
fruits.sort();
console.log(fruits);
Output
[ 'apple', 'banana', 'cherry', 'date' ]
sort()
converts array elements to strings and sorts them by their Unicode values.
2. Sorting Numbers with a Compare Function
To sort numbers correctly, a compare function must be provided.
const numbers = [30, 10, 20, 40];
// Ascending order
numbers.sort((a, b) => a - b);
console.log(numbers);
// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers);
Output
[10, 20, 30, 40]
[40, 30, 20, 10]
The compareFn
ensures numerical sorting. Without it, numbers are sorted as strings.
3. Sorting Strings in Descending Order
A compare function can also be used to sort strings in reverse alphabetical order.
const fruits = ["banana", "apple", "cherry", "date"];
fruits.sort((a, b) => b.localeCompare(a));
console.log(fruits);
Output
[ 'date', 'cherry', 'banana', 'apple' ]
4. Custom Sorting by Object Properties
Sorting objects can be achieved by providing a compare function that uses a specific property.
const items = [
{ name: "apple", price: 50 },
{ name: "banana", price: 20 },
{ name: "cherry", price: 30 },
];
// Sort by price in ascending order
items.sort((a, b) => a.price - b.price);
console.log(items);
Output
[
{ name: 'banana', price: 20 },
{ name: 'cherry', price: 30 },
{ name: 'apple', price: 50 }
]
The compareFn
compares the price
property of objects for sorting.
5. Sorting with Case-Insensitive Compare
To perform case-insensitive sorting, use toLowerCase()
or localeCompare()
in the compare function.
const fruits = ["Banana", "apple", "Cherry", "date"];
fruits.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(fruits);
Output
[ 'apple', 'Banana', 'Cherry', 'date' ]
This ensures that the sorting is case-insensitive.