Sub topic 5
Sorting Objects by Multiple Keys
Real data rarely sorts on one field. You might want a list of employees grouped by department, highest salary first within each department, and alphabetical by name when salaries tie. This chapter shows two ways to get that ordering: combining comparisons inside one comparator, and sorting in several passes that rely on stability.
It assumes you can write a single-key comparator that returns a negative, zero, or positive number, that you know toSorted returns a new array, and that you know sort has been stable since ES2019.
The core idea: fall through on ties
A multi-key comparator checks the primary key first. When that comparison gives a non-zero result, the order is decided and you return it. You check the secondary key only when the primary comparison returns 0, and the same rule applies to every key after that.
Chaining comparisons with ||
In JavaScript, 0 is falsy, so the || operator expresses "fall through on ties" in one line:
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']Writing b.age - a.age sorts ages in descending order. Cy and Ana are both 30, so the subtraction gives 0 and || moves on to the name comparison, which puts Ana first. You set the direction separately for each key by swapping a and b in that key's comparison.
The pattern works for any key type, provided each comparison returns a number:
| Key type | Ascending comparison |
|---|---|
| Number | `a.n - b.n` |
| String | `a.s.localeCompare(b.s)` |
| Date | `a.d - b.d` (subtraction converts Dates to timestamps) |
| Boolean | `Number(a.flag) - Number(b.flag)` |
A reusable comparator builder
If several screens sort the same data in different ways, small helper functions keep the comparators readable:
const by = (key, dir = 1) => (a, b) => {
const x = a[key];
const y = b[key];
const result = typeof x === 'string' ? x.localeCompare(y) : x - y;
return dir * result;
};
const thenBy = (...comparators) => (a, b) => {
for (const cmp of comparators) {
const r = cmp(a, b);
if (r !== 0) return r;
}
return 0;
};
const staff = [
{ name: 'Lee', dept: 'Sales', salary: 70000 },
{ name: 'Ari', dept: 'Eng', salary: 90000 },
{ name: 'Kim', dept: 'Sales', salary: 65000 },
{ name: 'Bea', dept: 'Eng', salary: 90000 }
];
const ordered = staff.toSorted(
thenBy(by('dept'), by('salary', -1), by('name'))
);
console.log(ordered.map(p => p.name)); // ['Ari', 'Bea', 'Lee', 'Kim']Eng comes before Sales. Ari and Bea tie on salary, so the name comparison breaks the tie. In Sales, Lee comes before Kim because the salary key is descending.
Multi-pass sorting with stability
A stable sort keeps tied elements in their existing order. That gives you a second technique: sort by the least important key first, then sort by each more important key in turn.
const tasks = [
{ title: 'Write docs', priority: 2 },
{ title: 'Fix bug', priority: 1 },
{ title: 'Add tests', priority: 2 },
{ title: 'Deploy', priority: 1 }
];
const result = tasks
.toSorted((a, b) => a.title.localeCompare(b.title))
.toSorted((a, b) => a.priority - b.priority);
console.log(result.map(t => t.title));
// ['Deploy', 'Fix bug', 'Add tests', 'Write docs']The second pass orders tasks by priority only. Tasks with the same priority stay in the alphabetical order that the first pass produced.
Common errors
- Putting keys in the wrong order for multi-pass sorting. The last pass decides the primary order. If you sort by priority first and title second, you get an alphabetical list.
- Subtracting strings.
'Bo' - 'Ana'evaluates toNaN. The sort treatsNaNas0, so the elements look equal and the order comes out wrong without any error. UselocaleComparefor strings. - Missing values. If some objects have no
age,undefined - 30evaluates toNaN, which breaks the comparator's consistency. Normalize these values first, for example(a.age ?? Infinity) - (b.age ?? Infinity)to put missing ages last. - Using
||with a comparison that returns a boolean.a.age > b.age || ...returnstrueorfalse, and the sort never sees a negative number. Every comparison in the chain must return a number.
Exercise
Given events shaped like { title: 'Launch', date: new Date('2026-03-01'), pinned: true }, write a toSorted call that puts pinned events first, then sorts by date ascending, then by title alphabetically.
Show answer
events.toSorted((a, b) => Number(b.pinned) - Number(a.pinned) || a.date - b.date || a.title.localeCompare(b.title)). Swapping a and b in the pinned comparison puts true (1) before false (0). Subtracting the dates compares their timestamps, and localeCompare breaks any remaining ties.
Exercise
With the multi-pass technique, you want rows ordered by country, then by city within each country. Which key do you sort by first, and why?
Show answer
Sort by city first, then by country. The stable second pass orders rows by country and keeps each country's rows in the city order produced by the first pass.