Sort by multiple keys
Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.
One sort order is rarely enough: you want the oldest people first, and the ones with the same age in alphabetical order. A comparator can express that by returning 0 on a tie and letting the next key decide.
const people = [
{ name: 'Ana', age: 31 },
{ name: 'Bo', age: 25 },
{ name: 'Cy', age: 31 },
{ name: 'Di', age: 25 },
];
const sorted = people.toSorted(
(a, b) => b.age - a.age || a.name.localeCompare(b.name),
);
console.log(sorted.map((p) => `${p.name} ${p.age}`).join(', '));Ana 31, Cy 31, Bo 25, Di 25The || works because 0 is falsy: when the ages are equal the first expression is 0 and the second one is evaluated. The comparator contract is described on Array.prototype.sort, and toSorted() needs Node.js 20. Since ES2019 the sort is stable, so equal elements keep their original order even without the second key.
Do not use || when a key comparison can return NaN, for example subtracting undefined: NaN is also falsy and the next key silently takes over. Compare numbers you have already checked.