Emmanuel Akinfulubi

JavaScriptArray

Sort an array of objects by property in JavaScript

Intermediate · 4 min read

Most real lists hold objects, not plain numbers: a list of staff, products or bookings. Sorting them means picking a property, like age or price, and comparing that. Often you need two keys at once: sort by department, and within each department by name. Every table with clickable column headers does this.

In this tutorial you will sort a staff list by age, then by department and name together. Along the way you will meet stability, a promise sort makes about records that tie. You should know objects, arrow functions and how a compare function works (negative means a first, positive means b first, zero means equal).

The data

Every step uses the same four people. Notice that two of them are 29 and two are 34, and that each department has two people.

JavaScript

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
console.log(staff.map((s) => s.name)); // [ 'Ada', 'Bola', 'Chi', 'Dami' ]

What stable means

A sort is stable when items that compare as equal keep the order they had before. If Bola came before Chi in the input and both are 29, a stable sort by age keeps Bola before Chi. JavaScript's sort has been required to be stable since the 2019 edition of the language, so you can rely on it.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

27 Sort records by a key, and by two keys

fair

Sort a list of people by age, then by department and age together. Then check what happens to two records that tie.

Stuck? Three hints, smallest first
  1. 1. One comparator per key, then a combinator that tries each in turn until one returns non-zero.
  2. 2. JavaScript’s sort is required to be stable: equal elements keep their original relative order.
  3. 3. That means sorting by the minor key first and the major key second gives the same answer as one combined comparator.

Step 1: sort by one number

Compare the age property of the two records. [...staff] copies the list first, because sort changes the array you call it on.

Step 1

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
const byAge = (a, b) => a.age - b.age;
const names = (list) => list.map((s) => s.name);
console.log(names([...staff].sort(byAge)));                     // [ 'Bola', 'Chi', 'Ada', 'Dami' ]
console.log(names([...staff].sort((a, b) => b.age - a.age))); // [ 'Ada', 'Dami', 'Bola', 'Chi' ]
console.log(names(staff));                                     // [ 'Ada', 'Bola', 'Chi', 'Dami' ]

names is a helper that prints just the names, so the output is easy to read. Look at the two 29s: Bola then Chi, the same order as the input. That is stability at work. For oldest first, flip the subtraction in the comparator.

Step 2: sort by any text key

For text, you can't subtract. byKey takes a property name and gives back a comparator for that property.

Step 2

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
const byKey = (key) => (a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0);
const names = (list) => list.map((s) => s.name);
console.log(names([...staff].sort(byKey('dept')))); // [ 'Bola', 'Dami', 'Ada', 'Chi' ]

byKey('dept') returns a function, and that function is the comparator. a[key] reads whichever property you named. A function that builds another function like this is a handy way to avoid writing the same comparator five times.

Step 3: two keys with thenBy

To break ties, try the first comparator, and only if it says "equal" (zero) try the next. thenBy does that for any number of comparators.

Step 3

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
const byKey = (key) => (a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0);
const thenBy = (...comparators) => (a, b) => {
  for (const cmp of comparators) {
    const verdict = cmp(a, b);
    if (verdict !== 0) return verdict;
  }
  return 0;
};
const names = (list) => list.map((s) => s.name);
console.log(names([...staff].sort(thenBy(byKey('dept'), byKey('name'))))); // [ 'Bola', 'Dami', 'Ada', 'Chi' ]

...comparators collects all the arguments into an array. The loop returns the first answer that isn't zero. If every comparator says equal, the result is zero. Adding a third key is just one more argument.

Step 4: two passes give the same answer

Stability gives you another way to do this. Sort by the less important key first, then by the more important one.

Step 4

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
const byKey = (key) => (a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0);
const names = (list) => list.map((s) => s.name);
console.log(names([...staff].sort(byKey('name')).sort(byKey('dept')))); // [ 'Bola', 'Dami', 'Ada', 'Chi' ]

The first sort puts names in order. The second sort groups by department, and because it is stable, people in the same department stay in name order. This is how clicking "name" and then "department" in a table can give a sensible result.

Step 5: a typo in the key

What if you misspell the property?

Step 5

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
];
const byKey = (key) => (a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0);
console.log([...staff].sort(byKey('nope')).map((s) => s.name)); // [ 'Ada', 'Bola' ]
console.log([...staff].sort(byKey('age'))[0] === staff[1]);     // true

Every record's nope is undefined, so every comparison returns zero and nothing moves. There is no error. The list just quietly stays as it was. The second line shows that the sorted copy holds the same objects as the original, not copies of them.

The full solution

The panel defines byAge, byKey and thenBy, then sorts by age, by department and name, and with two passes. Press Run and check that the two-key and two-pass lines agree.

The answer

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];

const byAge = (a, b) => a.age - b.age;
const byKey = (key) => (a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0);

// Try each comparator until one has an opinion.
const thenBy = (...comparators) => (a, b) => {
  for (const cmp of comparators) {
    const verdict = cmp(a, b);
    if (verdict !== 0) return verdict;
  }
  return 0;
};

const names = (list) => list.map((s) => s.name);
const sortedByAge = [...staff].sort(byAge);
const twoKeys = [...staff].sort(thenBy(byKey('dept'), byKey('name')));
const twoPasses = [...staff].sort(byKey('name')).sort(byKey('dept'));

console.log('by age            :', names(sortedByAge));
console.log('dept then name    :', names(twoKeys));
console.log('name, then re-sorted by dept:', names(twoPasses), '<- stability makes these agree');
console.log('by age descending :', names([...staff].sort((a, b) => b.age - a.age)));
console.log('original order    :', names(staff));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('sorting by a numeric key', names(sortedByAge), ['Bola', 'Chi', 'Ada', 'Dami']);
test('the two 29s kept their original order, which is stability', names(sortedByAge).slice(0, 2), ['Bola', 'Chi']);
test('a second comparator breaks the tie', names(twoKeys), ['Bola', 'Dami', 'Ada', 'Chi']);
test('two stable passes give the same answer as one combined comparator', names(twoPasses), names(twoKeys));
test('descending reverses the comparator, not the array', names([...staff].sort((a, b) => b.age - a.age)), ['Ada', 'Dami', 'Bola', 'Chi']);
test('sorting a copy leaves the original order alone', names(staff), ['Ada', 'Bola', 'Chi', 'Dami']);
test('the sorted list holds the same objects, not copies', sortedByAge[0] === staff[1], true);
test('a key that no record has leaves the order untouched', names([...staff].sort(byKey('nope'))), names(staff));
test('and a comparator returning 0 throughout is a no-op', [...staff].sort(() => 0).length, 4);

Stability is a guarantee, not luck: the specification has required it since ES2019. It is what makes the two-pass sort work — sort by name, then by department, and within each department the names are still in order because equal departments did not move.

thenBy is worth keeping in a utilities file. Written out longhand, multi-key sorting turns into nested ternaries that nobody can read six months later; as a list of comparators it stays obvious, and adding a third key is one more argument.

The last-but-one assertion is the quiet one: sorting by a key none of the records has compares undefined with undefined, returns 0 every time, and leaves the array exactly as it was. A typo in a key name therefore fails silently rather than loudly.

Common mistakes

  • Sorting the original list. staff.sort(...) reorders staff for everyone who uses it. Sort a copy.
  • Nesting ? : for several keys. It quickly becomes unreadable. A list of comparators in thenBy stays clear.
  • Doing two passes in the wrong order. Sort by the minor key first and the major key last, or the minor order is lost.

Try it yourself

  1. Sort staff by age, and by name when the ages tie.
  2. Sort by department from Z to A, then by age from youngest. (Hint: wrap byKey('dept') so it returns the opposite sign.)
  3. Change byKey so it throws an error when neither record has the key.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.