How to Sort Array of Objects by Two Fields in JavaScript

Published Feb 23, 2022  ∙  Updated May 2, 2022

Suppose we have an array of objects with two fields that we’d like to sort by.

const arr = [
  { id: 0, set: 0 },
  { id: 1, set: 1 },
  { id: 2, set: 2 },
  { id: 0, set: 3 },
  { id: 1, set: 4 },
  { id: 2, set: 5 },
];

We can sort by multiple fields easily using sort() and the OR operator ||.

Sort ascending by two fields

Let’s say we want to sort ascending by id, then sort ascending by set.

arr.sort((a,b) => a.id - b.id || a.set - b.set);

Sort ascending then descending

What if we wanted to sort ascending by id, then sort descending by set?

arr.sort((a,b) => a.id - b.id || b.set - a.set);

Sort descending by two fields

What if we wanted to sort descending by set, then sort descending by id?

arr.sort((a,b) => b.set - a.set || b.id - a.id);