Sub topic 5
Sorting Objects by Multiple Keys
Real data rarely sorts cleanly on one field. Two employees share a department, two orders share a date, two products share a price. Once the primary key ties, you need a rule for what comes next. This chapter shows how to build comparators that sort by several keys, mix ascending and descending order, handle missing values, and stay fast on large arrays.
This chapter assumes you can write a basic comparator (a function (a, b) that returns a negative number, zero, or a positive number). It also assumes you know that sort is stable since ES2019 and that toSorted returns a new array. Both topics have their own chapters. The same holds for localeCompare; here it is used only as a ready-made string comparator.
The Core Pattern: Chaining with ||
A multi-key comparator compares the first key. If those values differ, that result decides the order. If they are equal, it moves to the second key, and so on. In JavaScript the shortest way to write this uses the logical OR operator:
const people = [
{ name: 'Cy', age: 30 },
{ name: 'Bo', age: 25 },
{ name: 'Ana', age: 30 }
];
const byAgeDescThenName = people.toSorted(
(a, b) => b.age - a.age || a.name.localeCompare(b.name)
);
console.log(byAgeDescThenName.map(p => p.name)); // ['Ana', 'Cy', 'Bo']Why || works
|| returns its left operand if that operand is truthy. Otherwise it evaluates and returns the right operand. A comparator result of 0 is falsy, and every other number except NaN is truthy. So:
- If
b.age - a.ageis5or-5,||returns it right away and the name comparison never runs. - If the ages are equal, the subtraction gives
0, and||falls through toa.name.localeCompare(b.name).
You can extend the chain to as many keys as you need. Each || adds a tiebreaker:
const compare = (a, b) =>
a.department.localeCompare(b.department) ||
b.salary - a.salary ||
a.lastName.localeCompare(b.lastName) ||
a.id - b.id;Order the expressions from most important to least important. The last key is a common way to guarantee a fully deterministic order. A unique field like id works well here, because no two elements can tie on it.
Direction per key
Each key sets its own direction, which you choose by the order of the operands:
- Ascending:
a.key - b.keyora.key.localeCompare(b.key) - Descending:
b.key - a.keyorb.key.localeCompare(a.key)
In the first example, age is descending (b.age - a.age) and name is ascending (a.name.localeCompare(b.name)). Swapping a and b for one key does not affect the others.
Comparing Different Key Types
Each link in the chain must itself be a correct comparator for its key's type. This table lists the expressions that work for common types:
| Key type | Ascending expression | Notes |
|---|---|---|
| Number | `a.n - b.n` | Gives `NaN` if either value is missing or not numeric |
| String (human order) | `a.s.localeCompare(b.s)` | Locale-aware; reuse an `Intl.Collator` for large arrays |
| String (code unit order) | `a.s < b.s ? -1 : a.s > b.s ? 1 : 0` | Fast and locale-independent, but case-sensitive and accent-naive |
| Date object | `a.d - b.d` | Subtraction calls `valueOf`, giving milliseconds |
| ISO date string | `a.d.localeCompare(b.d)` or code unit compare | Works because `YYYY-MM-DD` strings sort in chronological order |
| Boolean | `a.flag - b.flag` | `false` (0) before `true` (1); use `b.flag - a.flag` for true first |
Booleans subtract cleanly because arithmetic converts true to 1 and false to 0. That makes "in stock first" or "pinned items first" an easy primary key:
const products = [
{ name: 'Lamp', inStock: false, price: 20 },
{ name: 'Desk', inStock: true, price: 150 },
{ name: 'Chair', inStock: true, price: 80 }
];
const sorted = products.toSorted(
(a, b) => b.inStock - a.inStock || a.price - b.price
);
console.log(sorted.map(p => p.name)); // ['Chair', 'Desk', 'Lamp']Common Errors with Chained Comparators
Using ?? instead of ||
The nullish coalescing operator ?? looks like a modern replacement for ||, but it falls through only on null or undefined. A comparator result of 0 is neither, so the tiebreaker never runs:
const people = [
{ name: 'Cy', age: 30 },
{ name: 'Ana', age: 30 }
];
const wrong = people.toSorted(
(a, b) => (a.age - b.age) ?? a.name.localeCompare(b.name)
);
console.log(wrong.map(p => p.name)); // ['Cy', 'Ana'] (tie kept in input order)
const right = people.toSorted(
(a, b) => (a.age - b.age) || a.name.localeCompare(b.name)
);
console.log(right.map(p => p.name)); // ['Ana', 'Cy']The wrong version runs without errors. Because the sort is stable, the output looks plausible, and the bug often goes unnoticed until real data exposes it.
Silent NaN from missing values
If a numeric field is undefined or null on some elements, subtraction can produce NaN. NaN is falsy, so || falls through to the next key as if the values were equal. The comparator then becomes inconsistent. For example, element A can be "equal" to B on price while B is less than C, which breaks the assumptions the sorting algorithm relies on. The result depends on the engine and the input order, and it can differ between runs on different data. Handle missing values on purpose (see the reusable comparator below) instead of letting NaN leak into the chain.
Returning booleans
(a, b) => a.age > b.age || a.name > b.name returns true or false, which convert to 1 or 0. It never returns a negative value, so it cannot express "a comes first". This mistake shows up more often in multi-key code, because chaining > comparisons with || reads naturally. Every link must return a signed number.
The Two-Pass Alternative: Relying on Stability
Because sort is stable, you can also sort by several keys in separate passes. Sort by the least important key first and the most important key last. Each later pass keeps the earlier order among its ties:
const people = [
{ name: 'Cy', age: 30 },
{ name: 'Bo', age: 25 },
{ name: 'Ana', age: 30 }
];
const twoPass = people
.toSorted((a, b) => a.name.localeCompare(b.name)) // secondary key first
.sort((a, b) => b.age - a.age); // primary key last
console.log(twoPass.map(p => p.name)); // ['Ana', 'Cy', 'Bo']The first pass produces Ana, Bo, Cy. The second pass sorts by age descending, and because the sort is stable, Ana stays ahead of Cy. Calling .sort on the result of toSorted is safe, because that array is already a copy.
Use the two-pass approach when the passes come from different places. A typical case is a table UI where the user clicks one column header after another, and each click sorts the current view by that column. For a fixed ordering known up front, one chained comparator is clearer. It is also faster, because it sorts once.
| Approach | Sorts performed | Best for |
|---|---|---|
| Chained comparator | 1 | Fixed, known key order |
| Multiple stable passes | One per key | Interactive or incremental re-sorting |
A Reusable Comparator Builder
When many parts of a codebase sort by different field combinations, hand-written chains get repetitive and easy to break. A small builder function centralizes the type handling, the direction, and the missing-value policy:
function sortBy(...specs) {
const rules = specs.map(spec =>
typeof spec === 'string' ? { key: spec, dir: 'asc' } : spec
);
return (a, b) => {
for (const { key, dir = 'asc' } of rules) {
const x = a[key];
const y = b[key];
if (x === y) continue;
if (x == null) return 1; // missing values last, in either direction
if (y == null) return -1;
let c;
if (typeof x === 'string' && typeof y === 'string') {
c = x.localeCompare(y);
} else {
c = x < y ? -1 : x > y ? 1 : 0;
}
if (c !== 0) return dir === 'desc' ? -c : c;
}
return 0;
};
}
const tasks = [
{ title: 'Write docs', priority: 2, due: new Date('2026-12-01') },
{ title: 'Fix login', priority: 1, due: new Date('2026-11-30') },
{ title: 'Review PR', priority: 1, due: new Date('2026-11-28') },
{ title: 'Plan sprint', priority: 2, due: null },
{ title: 'Deploy', priority: 1, due: new Date('2026-11-28') }
];
console.log(tasks.toSorted(sortBy('priority', 'due', 'title')).map(t => t.title));
// ['Deploy', 'Review PR', 'Fix login', 'Write docs', 'Plan sprint']
console.log(tasks.toSorted(sortBy({ key: 'priority', dir: 'desc' }, 'due')).map(t => t.title));
// ['Write docs', 'Plan sprint', 'Review PR', 'Deploy', 'Fix login']Some details of this builder are worth knowing:
- Missing values are handled before the direction is applied. The
nullcheck returns early, sonullandundefinedsort last whether the key is ascending or descending. If you negated those results too, missing values would jump to the front in descending sorts, which users rarely expect. - Dates work without special cases. Two distinct
Dateobjects with the same time failx === y, but<and>compare their numeric values. Both returnfalse, socis0and the loop moves to the next key. - Stability fills the final gap. In the second call, "Review PR" and "Deploy" tie on both priority and due date. No title key is given, so they keep their input order.
- NaN counts as equal to everything.
NaN < yandNaN > yare both false. If a numeric field can holdNaN, add an explicit check for it, the same way as fornull.
Performance: Precomputing Expensive Keys
A sort calls the comparator about n log n times. For 10,000 elements that is well over 100,000 calls, and each call computes the keys for both elements. If computing a key is expensive (parsing a date string, splitting a name, lowercasing, calling a lookup), that work gets repeated many times for the same element.
The fix is called decorate-sort-undecorate (also known as the Schwartzian transform). Compute each key once, sort the decorated wrappers, then unwrap them:
const users = [
{ fullName: 'grace Hopper', joined: '2021-03-04' },
{ fullName: 'Alan Turing', joined: '2020-07-19' },
{ fullName: 'Ada Lovelace', joined: '2021-03-04' }
];
const decorated = users.map(u => ({
u,
joined: Date.parse(u.joined),
last: u.fullName.split(' ').at(-1).toLowerCase()
}));
decorated.sort((a, b) => b.joined - a.joined || a.last.localeCompare(b.last));
const result = decorated.map(d => d.u.fullName);
console.log(result); // ['grace Hopper', 'Ada Lovelace', 'Alan Turing']Key extraction now runs n times instead of about 2n log n times. The cost is one extra array of small objects. For a few hundred elements with cheap keys, the plain chained comparator is fine. Measure before you add this step. For string keys, a shared Intl.Collator instance's compare is also faster than calling localeCompare repeatedly with options. The locale chapter covers this in detail.
Checklist
- Order the chain from most to least important key, and join the links with
||, never??. - Choose each key's direction by the operand order:
a, bfor ascending andb, afor descending. - Make every link return a signed number. Watch for
NaNfrom missing or non-numeric values. - End with a unique key if you need a fully deterministic order. Otherwise stability preserves the input order among ties.
- Precompute keys when extracting them is expensive and the array is large.
Exercise
Write a comparator for products (objects with inStock boolean, price number, name string) that puts in-stock items first, then sorts by price from lowest to highest, then by name alphabetically.
Show answer
(a, b) => b.inStock - a.inStock || a.price - b.price || a.name.localeCompare(b.name). b.inStock - a.inStock gives -1 when only a is in stock, which puts a first. Each later key is reached only when all earlier keys tie, because a result of 0 is falsy.
Exercise
A teammate writes (a, b) => (a.score - b.score) ?? a.name.localeCompare(b.name). Players with equal scores are not sorted by name. Why, and what is the fix?
Show answer
?? falls through only on null or undefined. A tie on score produces 0, which is neither, so the name comparison never runs and tied players keep their input order. Replace ?? with ||, which falls through on 0.
Exercise
You want employees ordered by department (A to Z), and within each department by salary from highest to lowest, using two separate stable sorts. Which sort do you run first, and why?
Show answer
Sort by salary descending first, then by department ascending. The last pass sets the primary order. Because the sort is stable, employees in the same department keep the salary order from the first pass.
Exercise
In the sortBy builder, why are the null checks performed before applying dir === 'desc' ? -c : c, instead of folding them into c?
Show answer
If the missing-value results were negated along with c, a descending sort would move null and undefined values to the front. Returning early keeps missing values at the end in both directions, which is usually what users expect.