The sort()
method sorts the elements of an array in place and returns the sorted array. The default sorting order is ascending.
Basic Usage of sort()
const fruits = ['Banana', 'Apple', 'Cherry']; fruits.sort(); console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
Key Points:
- By default,
sort()
converts elements to strings and sorts them alphabetically.
Sorting Numbers
When sorting numbers, the default sort()
may not work as expected because it converts numbers to strings before comparing them. To sort numbers numerically, you need to provide a compare function.
const numbers = [40, 100, 1, 5, 25, 10]; numbers.sort(); // Incorrect sorting console.log(numbers); // Output: [1, 10, 100, 25, 40, 5] numbers.sort((a, b) => a - b); // Correct sorting console.log(numbers); // Output: [1, 5, 10, 25, 40, 100]
Key Points:
- Ascending order: Use
(a, b) => a - b
. - Descending order: Use
(a, b) => b - a
.
Custom Sorting
You can provide a custom compare function to sort()
for more complex sorting logic.
const items = [ { name: 'Banana', price: 1.0 }, { name: 'Apple', price: 1.2 }, { name: 'Cherry', price: 0.8 } ]; items.sort((a, b) => a.price - b.price); console.log(items); // Output: [{ name: 'Cherry', price: 0.8 }, { name: 'Banana', price: 1.0 }, { name: 'Apple', price: 1.2 }]
Key Points:
- Sort by object properties by accessing them in the compare function.
Reversing an Array
To reverse the order of the elements in an array, use the reverse()
method.
const fruits = ['Banana', 'Apple', 'Cherry']; fruits.reverse(); console.log(fruits); // Output: ['Cherry', 'Apple', 'Banana']
Key Points:
reverse()
can be combined withsort()
to sort in descending order.
Sorting Arrays with localeCompare()
The localeCompare()
method can be used to sort strings in different locales and with different options.
const items = ['Banana', 'äpple', 'Cherry']; items.sort((a, b) => a.localeCompare(b)); console.log(items); // Output: ['äpple', 'Banana', 'Cherry']
Key Points:
localeCompare()
is useful for sorting strings with special characters or in different languages.
Summary
sort()
: Sorts elements of an array in place.- Custom compare function: Needed for numerical or complex sorting.
reverse()
: Reverses the elements in an array.localeCompare()
: Useful for string sorting with locale-specific comparisons.