JavaScript Array Sort
Sorting puts elements in order — names alphabetically, prices from low to high, dates from newest to oldest. JavaScript's sort() method does the work, but it has a famous trap with numbers that every developer needs to know.
Sorting strings
By default, sort() arranges elements as strings in ascending Unicode order. It sorts the array in place (mutating it) and also returns it:
const names = ["Mila", "anna", "Zoe", "Ben"];
names.sort();
console.log(names);[ 'Ben', 'Mila', 'Zoe', 'anna' ]
Uppercase letters come before lowercase ones in Unicode, so "anna" ends up last. For natural alphabetical order, compare with localeCompare:
const names = ["Mila", "anna", "Zoe", "Ben", "Émile"];
names.sort((a, b) => a.localeCompare(b, "en"));
console.log(names);[ 'anna', 'Ben', 'Émile', 'Mila', 'Zoe' ]
The number trap
Because the default sort compares strings, numbers are sorted "alphabetically" — "10" comes before "9" because "1" < "9":
const nums = [10, 9, 1, 100, 25];
console.log([...nums].sort()); // wrong for numbers
console.log([...nums].sort((a, b) => a - b)); // ascending
console.log([...nums].sort((a, b) => b - a)); // descending[ 1, 10, 100, 25, 9 ]
[ 1, 9, 10, 25, 100 ]
[ 100, 25, 10, 9, 1 ]
Compare functions
A compare function receives two elements a and b and returns:
| Return value | Meaning |
|---|---|
| negative | a comes before b |
| positive | a comes after b |
0 |
keep their relative order |
a - b is a short way to produce exactly that for numbers. Since 2019 sort is guaranteed stable: elements that compare equal keep their original order.
Sorting objects
Compare a property of each object. To sort by several keys, fall through to the next key when the first is equal:
const students = [
{ name: "Lea", grade: 2, age: 15 },
{ name: "Max", grade: 1, age: 16 },
{ name: "Ivy", grade: 2, age: 14 },
{ name: "Ken", grade: 1, age: 15 },
];
const byGradeThenAge = [...students].sort((a, b) => a.grade - b.grade || a.age - b.age);
for (const s of byGradeThenAge) {
console.log(s.grade, s.age, s.name);
}
const byName = students.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName.map((s) => s.name).join(", "));1 15 Ken
1 16 Max
2 14 Ivy
2 15 Lea
Ivy, Ken, Lea, Max
a.grade - b.grade || a.age - b.age works because 0 (equal grades) is falsy, so || moves on to compare ages.
Reversing, and sorting without mutating
reverse() flips the order in place. Since sort and reverse mutate, copy first with [...arr] — or use the newer toSorted() and toReversed(), which return new arrays:
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
const reversed = original.toReversed();
console.log(original, sorted, reversed);
original.sort((a, b) => a - b).reverse(); // chain on the same array
console.log(original);[ 3, 1, 2 ] [ 1, 2, 3 ] [ 2, 1, 3 ]
[ 3, 2, 1 ]
Minimum and maximum
You don't need to sort just to find the smallest or largest value — Math.min / Math.max with spread is simpler and faster:
const temps = [12, 19, 7, 23];
Math.min(...temps); // 7
Math.max(...temps); // 23Note: Don't shuffle an array with
sort(() => Math.random() - 0.5)— the result is biased. Use the Fisher–Yates algorithm instead.
Test yourself
What does [5, 20, 3].sort() produce?
- [3, 5, 20]
- [20, 5, 3]
- [20, 3, 5]
- [3, 20, 5]
Which compare function sorts numbers in descending order?
- (a, b) => a - b
- (a, b) => b - a
- (a, b) => a > b
- (a, b) => 0
Which method sorts without changing the original array?
- sort()
- reverse()
- toSorted()
- splice()