Sub topic 12
Sorting Correctly with Comparator Functions
This chapter assumes you already know how array callbacks receive their arguments, and that you can tell mutating methods from non-mutating ones. Both topics were covered in earlier chapters. You should also be comfortable with arrow functions and object property access.
Sorting looks simple, but sort() has two behaviors that surprise people. It changes the original array, and by default it compares values as strings. This chapter explains both behaviors, shows how comparator functions fix them, and covers the edge cases that lead to subtle bugs.
What sort() Actually Does
Array.prototype.sort() reorders the elements of an array in place. It rearranges the array you called it on and returns a reference to that same array. It does not return a copy.
const scores = [42, 7, 19];
const result = scores.sort((a, b) => a - b);
console.log(result); // [7, 19, 42]
console.log(scores); // [7, 19, 42]
console.log(result === scores); // trueBecause result and scores are the same object, code that expects to keep the original order is now broken. If you need the original order later, sort a copy instead. Two ways to do that:
const scores = [42, 7, 19];
const sortedA = [...scores].sort((a, b) => a - b); // copy, then sort
const sortedB = scores.toSorted((a, b) => a - b); // ES2023, returns a new array
console.log(sortedA); // [7, 19, 42]
console.log(sortedB); // [7, 19, 42]
console.log(scores); // [42, 7, 19]toSorted() accepts the same comparator as sort(). It is covered with the other copying methods in a later chapter. Everything in this chapter about comparators applies to both.
The Default Order Is String Order
When you call sort() with no argument, JavaScript converts each element to a string and compares those strings by their UTF-16 code units. For numbers, this almost never gives the order you want.
console.log([10, 1, 5, 100, 25].sort()); // [1, 10, 100, 25, 5]The string "100" comes before "25" because the character "1" comes before "2". The numeric values play no part in the comparison.
Strings get a different surprise. Code-unit order puts all uppercase letters before all lowercase letters, and accented characters land after z:
console.log(['banana', 'apple', 'Cherry', 'éclair'].sort());
// ['Cherry', 'apple', 'banana', 'éclair']The default is only safe when every element is a string and you actually want raw code-unit order. That is rare. In practice, pass a comparator.
The Comparator Contract
A comparator is a function (a, b) => number. sort() calls it many times with pairs of elements and uses the sign of the return value to decide their relative order.
| Return value | Meaning |
|---|---|
| Negative (for example `-1`) | `a` goes before `b` |
| Positive (for example `1`) | `a` goes after `b` |
| `0` | `a` and `b` are equal; keep their existing relative order |
Only the sign matters. Returning -1 and returning -500 mean the same thing.
Numbers: subtract
For numbers, subtraction produces exactly the sign you need:
const nums = [10, 1, 5, 100, 25];
console.log([...nums].sort((a, b) => a - b)); // [1, 5, 10, 25, 100] ascending
console.log([...nums].sort((a, b) => b - a)); // [100, 25, 10, 5, 1] descendingIf a is smaller, a - b is negative, so a goes first. Swapping the operands reverses the order.
Subtraction also works for Date objects, because a Date converts to its timestamp in arithmetic:
const dates = [new Date('2024-03-01'), new Date('2023-12-25'), new Date('2024-01-15')];
dates.sort((a, b) => a - b);
console.log(dates.map(d => d.toISOString().slice(0, 10)));
// ['2023-12-25', '2024-01-15', '2024-03-01']Strings: localeCompare and Intl.Collator
You cannot subtract strings. Use localeCompare, which returns a negative number, zero, or a positive number according to the language's sorting rules:
const words = ['banana', 'apple', 'Cherry', 'éclair'];
console.log([...words].sort((a, b) => a.localeCompare(b)));
// ['apple', 'banana', 'Cherry', 'éclair']localeCompare accepts a locale and options. The numeric option compares runs of digits as numbers, which fixes file-name style sorting:
const files = ['file10.txt', 'file2.txt', 'file1.txt'];
console.log([...files].sort());
// ['file1.txt', 'file10.txt', 'file2.txt']
console.log([...files].sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));
// ['file1.txt', 'file2.txt', 'file10.txt']For large arrays, create an Intl.Collator once and reuse its compare method. Calling localeCompare with options sets up the locale rules again on every call, which is slower.
const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
const names = ['item20', 'Item3', 'item100'];
console.log(names.sort(collator.compare)); // ['Item3', 'item20', 'item100']collator.compare is already bound to its collator, so you can pass it directly as the comparator.
Sorting Objects by a Property
Most real sorting involves objects. The comparator reads the property you care about:
const products = [
{ name: 'Lamp', price: 30 },
{ name: 'Desk', price: 120 },
{ name: 'Chair', price: 85 }
];
const byPrice = products.toSorted((a, b) => a.price - b.price);
console.log(byPrice.map(p => p.name)); // ['Lamp', 'Chair', 'Desk']
const byName = products.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName.map(p => p.name)); // ['Chair', 'Desk', 'Lamp']Sorting by several keys
To sort by one key and break ties with another, compare the first key and fall back to the second only when the first returns 0. The || operator does this neatly, because 0 is falsy:
const staff = [
{ dept: 'Sales', name: 'Zoe' },
{ dept: 'Eng', name: 'Mia' },
{ dept: 'Sales', name: 'Adam' },
{ dept: 'Eng', name: 'Leo' }
];
staff.sort((a, b) =>
a.dept.localeCompare(b.dept) || a.name.localeCompare(b.name)
);
console.log(staff.map(s => `${s.dept}:${s.name}`));
// ['Eng:Leo', 'Eng:Mia', 'Sales:Adam', 'Sales:Zoe']You can chain as many || fallbacks as you need. To sort one key in descending order, swap a and b for that key only.
Stability
A sort is stable if elements that compare as equal keep their original relative order. Since ES2019, the specification requires sort() to be stable, and all current engines comply.
const people = [
{ name: 'Ana', age: 30 },
{ name: 'Ben', age: 25 },
{ name: 'Cleo', age: 30 },
{ name: 'Dan', age: 25 }
];
people.sort((a, b) => a.age - b.age);
console.log(people.map(p => p.name)); // ['Ben', 'Dan', 'Ana', 'Cleo']Ben stays ahead of Dan, and Ana stays ahead of Cleo, because that was their order before the sort. Stability lets you sort in several passes: sort by the secondary key first, then by the primary key. The multi-key comparator shown above is usually clearer, though.
Comparator Mistakes That Break Sorting
Returning a boolean
A common mistake is writing (a, b) => a > b. That returns true or false, which convert to 1 and 0. The comparator never returns a negative number, so sort() gets incomplete information. The result depends on the engine and the input. It may look correct on small arrays and fail on larger ones. Always return a number with a meaningful sign.
Inconsistent comparators
The algorithm assumes your comparator behaves consistently. If compare(a, b) is negative, then compare(b, a) must be positive. If a < b and b < c, then a < c must hold. Comparators that use randomness or read changing state break these rules. The result is then implementation-defined, so you get an order that is not reliably sorted.
The well-known shuffle arr.sort(() => Math.random() - 0.5) breaks the rules for exactly this reason. It produces a biased shuffle. Use a Fisher–Yates loop if you need a fair shuffle.
NaN values
If a property can be missing, a.price - b.price may produce NaN. sort() treats NaN as 0, so those elements are "equal" to everything, which makes the comparator inconsistent. Normalize the values first, for example with (a.price ?? Infinity) - (b.price ?? Infinity) to push missing prices to the end.
undefined and holes
sort() handles undefined itself. It moves every undefined element to the end of the array without ever passing it to your comparator. Empty slots in sparse arrays go after those undefined values.
const mixed = [3, undefined, 1, 2];
console.log(mixed.sort((a, b) => a - b)); // [1, 2, 3, undefined]null gets no such treatment. It reaches your comparator and converts to 0 in arithmetic, so guard against it explicitly.
Choosing an Approach
| Data | Comparator | Column | Column | Column | Column |
|---|---|---|---|---|---|
| Numbers or Dates, ascending | `(a, b) => a - b` | ||||
| Numbers or Dates, descending | `(a, b) => b - a` | ||||
| Human-readable strings | `(a, b) => a.localeCompare(b)` | ||||
| Strings with embedded numbers | `Intl.Collator` with `{ numeric: true }` | ||||
| Objects, several keys | First key `\ | \ | ` second key `\ | \ | ` ... |
| Need the original order kept | `toSorted(...)` or `[...arr].sort(...)` |
Exercise
What does [3, 20, 100].sort() return, and why? Write the call that sorts it numerically in descending order without changing the original array.
Show answer
It returns [100, 20, 3]. That happens to look descending, but only because the strings "100", "20", "3" are in code-unit order ("1" < "2" < "3"). With different data, such as [3, 20, 4], the result would be [20, 3, 4]. The correct descending copy is [3, 20, 100].toSorted((a, b) => b - a) (or [...arr].sort((a, b) => b - a)), which returns [100, 20, 3] and leaves the original untouched.
Exercise
Given const tasks = [{ title: 'b', priority: 2 }, { title: 'a', priority: 1 }, { title: 'c', priority: 2 }], write a comparator that sorts by priority descending, then by title ascending. What order results?
Show answer
tasks.sort((x, y) => (y.priority - x.priority) || x.title.localeCompare(y.title)). The result is b (priority 2), c (priority 2), then a (priority 1). The priority comparison puts both priority-2 tasks first, and the title fallback orders b before c.
Exercise
A teammate writes items.sort((a, b) => a.score > b.score). Why is this unreliable, and how do you fix it?
Show answer
The comparator returns a boolean, which converts to 1 or 0 and is never negative, so sort() cannot tell when a should come before b. The result depends on the engine and the input size. Fix it by returning a signed number: items.sort((a, b) => a.score - b.score).