Sort an array of objects by a property in JavaScript

By

Learn how to sort a JavaScript array of objects by a property value, using sort() with a callback that compares the values and returns 1 or -1 for the order.

~~~

To sort an array of objects by a property, call the array’s sort() method with a callback that compares that property on two objects and returns 1 or -1.

Say you have an array of objects like this:

const list = [
  { color: 'white', size: 'XXL' },
  { color: 'red', size: 'XL' },
  { color: 'black', size: 'M' }
]

You want to render this list, but first you want to order it by the value of one of the properties. For example you want to order it by the color name, in alphabetical order: black, red, white.

You can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b):

list.sort((a, b) => (a.color > b.color) ? 1 : -1)

When we return 1, the function communicates to sort() that the object b takes precedence in sorting over the object a. Returning -1 would do the opposite.

Note that sort() sorts the array in place. The original order is gone. If you need to keep it, sort a copy instead:

const sorted = [...list].sort((a, b) => (a.color > b.color) ? 1 : -1)

Sorting by a number property

For numbers, there’s a shorter comparator. Subtract the two values:

const products = [
  { name: 'Keyboard', price: 100 },
  { name: 'Mouse', price: 20 },
  { name: 'Cable', price: 9 }
]

products.sort((a, b) => a.price - b.price)
// Cable (9), Mouse (20), Keyboard (100)

A negative result means a comes first, a positive one means b comes first. Same idea as returning 1 and -1, with less code.

Watch out for uppercase letters

The > comparison works on character code points, and every uppercase letter comes before every lowercase one. So 'Red' sorts before 'black', which is rarely what you want.

If your data mixes cases, use localeCompare(), which compares strings the way a human would:

list.sort((a, b) => a.color.localeCompare(b.color))

Sorting by two properties

The callback function could calculate other properties too, to handle the case where the color is the same, and order by a secondary property as well:

list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 )

If you want to build a comparator like this without writing it by hand, try the sort comparator builder.

~~~

Related posts about js: