How to sort an array of objects by attribute value in JavaScript

Learn how to sort an array of objects by property values in JavaScript

Suppose 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 present this list, but first you need to sort it by the value of one of the attributes. For example, you want to sort by color name (in alphabetical order): black, red, white.

you can use itsort()MethodsArray, It comes with a callback function that takes 2 objects contained in the array as parameters (we call itawithb):

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

When we return 1, the function will be the same assort()The objectbPrioritize object sortinga. Return-1in contrast.

The callback function can also calculate other attributes to handle the case of the same color, and sort by secondary attributes:

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

Download mine for freeJavaScript beginner's manual

More js tutorials: