Skip to content
jshacks.dev
Fundamentals

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.

1 min read
Summarize in AI

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.

JavaScript
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(', '));
Text
Ana 31, Cy 31, Bo 25, Di 25

The || 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.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read
Fundamentals

Create a URL with search params

Build a URL with query parameters using URL and searchParams, and see how spaces and ampersands are encoded, plus how to resolve a relative path. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.