Sort By Two Fields in JavaScript


Here's how to sort an array of objects by two fields in JavaScript. This is sometimes called a secondary sort.

If you sort by multiple fields, it means that the first field is the primary thing to sort by, and the next is secondary, and so on.

The only reason you'd get to a secondary sort is if the primary sort field is equal in two objects being compared.

Here's a code example, where age is the primary and name is the secondary sort field:

function sortByAgeAscThenNameAlpha<
  T extends { age: number; name: string },
>(a: T, b: T): number {
  if (a.age === b.age) {
    if (a.name == b.name) return 0
    return a.name - b.name
  }
  return a.age - b.age
}

Here's an unordered data set to test:

const data = [
  { age: 20, name: 'Bob' },
  { age: 30, name: 'David' },
  { age: 40, name: 'Frank' },
  { age: 20, name: 'Alice' },
  { age: 30, name: 'Charlie' },
  { age: 40, name: 'Eve' },
]
data.sort(sortByAgeAscThenNameAlpha)

And here would be the result:

[
  { age: 20, name: 'Alice' },
  { age: 20, name: 'Bob' },
  { age: 30, name: 'Charlie' },
  { age: 30, name: 'David' },
  { age: 40, name: 'Eve' },
  { age: 40, name: 'Frank' }
]

Ordered. Doubly.