Order Your Items
JavaScript Array Sort
`sort` orders an array — but its defaults will surprise you with numbers. Pass a comparator function to get the order you want.
What you'll learn
- Sort strings with the default `sort`
- Sort numbers correctly with a comparator
- Sort objects by a field
- Know about `toSorted` for non-mutating sorts
sort reorders an array in place. For strings, the default works
fine. For numbers, you’ll get a surprise unless you pass a function.
Default Sort: Alphabetical
const fruits = ["banana", "apple", "grape", "cherry"];
fruits.sort();
console.log(fruits);
// ["apple", "banana", "cherry", "grape"] That’s the helpful case. Now the surprise:
const nums = [10, 1, 2, 21, 3];
nums.sort();
console.log(nums);
// [1, 10, 2, 21, 3] ← 😱 JavaScript’s default sort converts every item to a string and
compares lexicographically. "10" comes before "2" because "1"
comes before "2".
Fix: Pass a Comparator
sort takes a function that compares two items. It should return:
- A negative number if
ashould come beforeb - A positive number if
ashould come afterb 0if their order doesn’t matter
For numbers, a - b does exactly this:
const nums = [10, 1, 2, 21, 3];
nums.sort((a, b) => a - b);
console.log(nums); // [1, 2, 3, 10, 21] ✅
// Descending:
nums.sort((a, b) => b - a);
console.log(nums); // [21, 10, 3, 2, 1] Sorting Objects by a Field
The comparator pattern extends naturally to objects.
const users = [
{ name: "Lin", age: 28 },
{ name: "Ada", age: 36 },
{ name: "Tim", age: 12 },
];
// By age ascending:
users.sort((a, b) => a.age - b.age);
console.log(users);
// Tim (12), Lin (28), Ada (36)
// By name alphabetically:
users.sort((a, b) => a.name.localeCompare(b.name));
console.log(users);
// Ada, Lin, Tim sort Mutates the Array
sort changes the array in place AND returns it. This trips people up
when they want to keep the original around.
const original = [3, 1, 2];
const sorted = original.sort((a, b) => a - b);
console.log(sorted); // [1, 2, 3]
console.log(original); // [1, 2, 3] ← also changed
console.log(sorted === original); // true — same array! toSorted — A Non-Mutating Sort (ES2023)
When you want a sorted copy without disturbing the original, use
toSorted.
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
console.log(sorted); // [1, 2, 3]
console.log(original); // [3, 1, 2] ← unchanged There are matching non-mutating versions for the other in-place
operations: toReversed, toSpliced, with.
Reversing
reverse flips the order — also mutates.
const a = [1, 2, 3];
a.reverse();
console.log(a); // [3, 2, 1]
// Non-mutating version:
const b = [1, 2, 3];
const flipped = b.toReversed();
console.log(b); // [1, 2, 3]
console.log(flipped); // [3, 2, 1] End of Chapter
You can now hold and shape data. Next chapter: make programs decide and repeat.
Next chapter: Control Flow →