Sorting Arrays
Sorting puts an array's items in order: smallest fee first, names alphabetically, newest payment on top. JavaScript's sort method does it in place and is stable, but its default behavior surprises almost everyone: without a compare function, it sorts every value as a string, so [10, 9, 1].sort() gives [1, 10, 9]. Always give sort a compare function, and use toSorted when you need a sorted copy.
In One Minute
arr.sort(compareFn)sorts in place and returns the same array.- Without
compareFn, items are converted to strings and compared by UTF-16 code units: numbers sort wrongly. - Numbers ascending:
(a, b) => a - b. Descending:(a, b) => b - a. - Strings for people:
(a, b) => a.localeCompare(b). Objects: compare a property. toSorted(compareFn)andtoReversed()(ES2023) return sorted or reversed copies;reverse()reverses in place.
The Default Sort Is a String Sort
console.log([10, 9, 1, 100, 25].sort());
console.log(["banana", "Cherry", "apple"].sort());
console.log([true, false, null, undefined, 3].sort());[1, 10, 100, 25, 9]
['Cherry', 'apple', 'banana']
[3, false, null, true, undefined]Explanation: the default sort turns each item into a string and compares character codes. "10" comes before "9" because "1" comes before "9". Uppercase letters come before all lowercase ones, so "Cherry" is first. undefined values always go to the end. This default exists for historical reasons and is almost never what you want.
The Compare Function
A compare function takes two items, a and b, and returns a number that tells sort their order:
| Return value | Meaning |
|---|---|
Negative (< 0) | a comes before b |
Positive (> 0) | a comes after b |
0 | Keep their current order |
Numbers
Subtracting gives exactly that kind of number:
const fees = [120, 85, 450, 45, 200];
console.log([...fees].sort((a, b) => a - b));
console.log([...fees].sort((a, b) => b - a));[45, 85, 120, 200, 450]
[450, 200, 120, 85, 45]a - b is negative when a is smaller, so smaller numbers come first (ascending). b - a reverses it. The [...fees] copies the array first, because sort changes the array it is called on.
Strings
Use localeCompare, which returns a negative, zero or positive number in dictionary order:
const names = ["srihitha", "Navika", "advitha", "Émile"];
console.log([...names].sort((a, b) => a.localeCompare(b, "en-US")));
console.log([...names].sort((a, b) => b.localeCompare(a, "en-US")));['advitha', 'Émile', 'Navika', 'srihitha']
['srihitha', 'Navika', 'Émile', 'advitha']Objects by a Property
const payments = [
{ name: "Srihitha", amount: 85, date: "2026-01-12" },
{ name: "Navika", amount: 120, date: "2026-01-05" },
{ name: "Advitha", amount: 45, date: "2026-01-20" },
];
const byAmount = payments.toSorted((a, b) => b.amount - a.amount);
console.log(byAmount.map((p) => p.name));
const byName = payments.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName.map((p) => p.name));
const byDate = payments.toSorted((a, b) => a.date.localeCompare(b.date));
console.log(byDate.map((p) => p.date));['Navika', 'Srihitha', 'Advitha']
['Advitha', 'Navika', 'Srihitha']
['2026-01-05', '2026-01-12', '2026-01-20']Dates stored as ISO strings (YYYY-MM-DD) sort correctly as strings, which is one of many reasons to store dates that way. For Date objects, compare their timestamps: (a, b) => a.date - b.date.
Sorting by Several Keys
To sort by grade, then by name within each grade, compare the first key and fall back to the second only when the first is equal. The || operator does this neatly, because 0 is falsy:
const students = [
{ name: "Srihitha", grade: 11 },
{ name: "Navika", grade: 9 },
{ name: "Advitha", grade: 11 },
{ name: "Zoe", grade: 9 },
];
const sorted = students.toSorted(
(a, b) => a.grade - b.grade || a.name.localeCompare(b.name)
);
console.log(sorted.map((s) => `${s.grade} ${s.name}`));['9 Navika', '9 Zoe', '11 Advitha', '11 Srihitha']Sorting Is Stable
Since ES2019, sort is guaranteed to be stable: items that compare as equal keep their original relative order. This lets you sort in stages. Sorting by name first and then by grade leaves each grade's students in name order:
const students = [
{ name: "Srihitha", grade: 11 },
{ name: "Navika", grade: 9 },
{ name: "Advitha", grade: 11 },
];
const result = students
.toSorted((a, b) => a.name.localeCompare(b.name))
.toSorted((a, b) => a.grade - b.grade);
console.log(result.map((s) => s.name));['Navika', 'Advitha', 'Srihitha']In Place vs Copy
| Changes the array | Returns a copy (ES2023) |
|---|---|
sort(fn) | toSorted(fn) |
reverse() | toReversed() |
const fees = [120, 45, 85];
const sorted = fees.sort((a, b) => a - b);
console.log(sorted === fees);
console.log(fees);
const original = [120, 45, 85];
const copy = original.toSorted((a, b) => a - b);
console.log(original, copy);
console.log(original.toReversed(), original);true
[45, 85, 120]
[120, 45, 85] [45, 85, 120]
[85, 45, 120] [120, 45, 85]Explanation: sort returns the same array it changed, which tricks people into thinking they got a sorted copy while the original was also reordered. toSorted and toReversed leave the original alone.
Common Mistakes
No compare function on numbers. [10, 9, 1].sort() gives [1, 10, 9]. Use (a, b) => a - b.
A compare function that returns a boolean. (a, b) => a > b returns true/false, which become 1/0. It never returns a negative number, so the result is wrong in most engines. Return a number.
Sorting shared data in place. Use toSorted.
Sorting strings with -. "b" - "a" is NaN. Use localeCompare.
Under the Hood
V8 implements sort with TimSort, a hybrid of merge sort and insertion sort (since V8 7.0 in 2018). TimSort is stable, runs in O(n log n) time in the worst case, and is especially fast on data that is already partly sorted, which real data often is. It finds existing ordered runs and merges them.
A compare function must be consistent: if a < b and b < c, then a < c, and compare(a, b) must always give the same answer for the same pair. A random comparator such as () => Math.random() - 0.5 breaks that rule. It doesn't produce a fair shuffle and can give badly skewed results. To shuffle, use the Fisher-Yates algorithm: walk the array from the end, swapping each item with a random earlier one (including itself).
Interview Corner
Why does [10, 9, 1].sort() return [1, 10, 9]?
Without a comparator, Array.prototype.sort converts elements to strings and compares UTF-16 code unit sequences. "10" sorts before "9" because "1" (U+0031) is less than "9" (U+0039). Pass (a, b) => a - b.
Is Array.prototype.sort stable?
Yes, since ES2019 the specification requires it. Elements that compare equal keep their original relative order, so multi-stage sorts work.
What is the difference between sort and toSorted?
sort reorders the array in place and returns the same reference. toSorted (ES2023) returns a new sorted array and leaves the original unchanged, which is safer for shared data and immutable state updates.
Practice
Challenge: Sort these payments so unpaid ones come first, and within each group the largest amount comes first. Don't change the original array.
Show solution
const payments = [
{ name: "Navika", amount: 120, paid: true },
{ name: "Srihitha", amount: 85, paid: false },
{ name: "Advitha", amount: 450, paid: false },
{ name: "Zoe", amount: 300, paid: true },
];
const ordered = payments.toSorted(
(a, b) => Number(a.paid) - Number(b.paid) || b.amount - a.amount
);
console.log(ordered.map((p) => `${p.paid ? "paid" : "due"} ${p.name} ${p.amount}`));
console.log(payments[0].name);['due Advitha 450', 'due Srihitha 85', 'paid Zoe 300', 'paid Navika 120']
NavikaKey Takeaways
| Sort | Compare function |
|---|---|
| Numbers ascending | (a, b) => a - b |
| Numbers descending | (a, b) => b - a |
| Names A to Z | (a, b) => a.localeCompare(b) |
| By property | (a, b) => a.amount - b.amount |
| Two keys | (a, b) => a.x - b.x || a.y.localeCompare(b.y) |
Was this tutorial helpful?