How to sort an array of objects by a property value in JavaScript

Imagine you have a collection of these objects:

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

This list is to be rendered. However, first you need to order it according to the value of one property. You might order it alphabetically by color names, such as black, red and white.

The  sort()method of Array, takes a callback function that takes two objects in the array as parameters (which we refer to as  a and b)

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

Returning 1 tells  sort()  that object b  is the priority in sorting. The opposite would be true if you returned -1.

To handle cases where the color is identical, or order by secondary properties, the callback function can also calculate other properties:

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

 

How Lack of Rest Can Impact Your Finances Small Businesses Can Enhance File Management Following these Tips How Much Do Real Estate Agents Spend on Marketing? How to Engage Your Online Audience for Long-Lasting Success Why is Plagiarism Such a Big Deal? Resume Service Review: Why Everyone Should Use It
adbanner