How to sort an array
Short answer
For numbers, pass a comparison function to sort():
console.log([10, 9, 1].sort((a, b) => a - b).join(', '));Output:
1, 9, 10Descending order
Swap a and b:
console.log([10, 9, 1].sort((a, b) => b - a).join(', '));Output:
10, 9, 1Strings
localeCompare() compares strings using the rules of a language:
console.log(['apple', 'Pear', 'avocado'].sort((a, b) => a.localeCompare(b, 'en')).join(', '));Output:
apple, avocado, PearBy an object field
Access the property you need inside the comparison function:
const users = [
{ name: 'Anna', age: 30 },
{ name: 'Oleg', age: 25 },
];
users.sort((a, b) => a.age - b.age);
console.log(users.map((user) => user.name).join(', '));Output:
Oleg, AnnaKeeping the original array
sort() modifies the array itself. To keep the original order, sort a copy:
const numbers = [3, 1, 2];
const sorted = [...numbers].sort((a, b) => a - b);
console.log(numbers.join(', '));
console.log(sorted.join(', '));Output:
3, 1, 2
1, 2, 3Common mistake
Without a comparison function, sort() compares numbers as strings:
console.log([10, 9, 1, 100].sort().join(', '));Output:
1, 10, 100, 9Functions used in this recipe
- Array.prototype.sort — Sorts the elements of an array.
- Array.prototype.toSorted — Returns a sorted copy of an array without changing the original.
- String.prototype.localeCompare — Compares strings by language rules — for alphabetical sorting.