How to Sort Array of Objects Based on Object Key in JavaScript

Published Feb 16, 2022  ∙  Updated May 2, 2022

How can we sort an array of objects based on the object key in JavaScript?

Suppose we have an array of objects arrOfObjs.

const arrOfObjs = [
  { id: 1, count, 1 },
  { id: 2, count, 3 },
  { id: 3, count, 5 },
  { id: 4, count, 7 },
  { id: 5, count, 9 }

How can we sort this array based on the count field?

Sort objects using sort()

We can use sort() to sort an array.

If we run arr.sort() without any arguments, each array element will be converted to a string and then sorted based on the Unicode encoding standard.

We can override the comparator function to define our own sort order.

arrOfObjs.sort((a, b) => a.count - b.count);

Note that sort() will sort the array in place. No copy will be made.

Sort ascending or descending

The comparator function’s job is to determine which of the two elements passed in the arguments will come first.

To do this, it returns an integer.

  • Negative: first argument comes first
  • Positive: second argument comes first
  • Zero: arguments are equal

In order to sort in ascending order, we’ll want to subtract the second argument from the first.

// Ascending order
arrOfObjs.sort((a, b) => a.count - b.count);

In order to sort in descending order, we’ll want to subtract the first argument from the second.

// Descending order
arrOfObjs.sort((a, b) => b.count - a.count);