AI Workshop: learn to build apps with AI →
Objects: Sort an array of objects by a property value

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


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 2 objects from the array as parameters (we call them a and b):

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

When the callback returns 1, it tells sort() that b should come after a. Returning -1 does the opposite.

The callback can also compare other properties, 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 )

Lessons in this unit:

0: Introduction
1: How to create an object
2: Object properties
3: Objects are passed by reference
4: Methods
5: Passing objects as function arguments or returning objects from a function
6: Accessing a property of the object inside a method using `this`
7: Object destructuring
8: Cloning objects
9: ▶︎ Sort an array of objects by a property value
10: Merging two objects into one
11: apply, call, bind