/

How to Sort an Array of Objects by a Property Value in JavaScript

How to Sort an Array of Objects by a Property Value in JavaScript

In JavaScript, it is often necessary to sort an array of objects by a specific property value. Let’s explore how to achieve this!

Suppose you have an array of objects like this:

1
2
3
4
5
const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
]

To order this list by the value of a property, such as the color name in alphabetical order, you can use the sort() method of the Array. The sort() method takes a callback function that compares two objects in the array (referred to as a and b):

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

The callback function returns 1 if b needs to be placed before a in the sorted array. If a needs to come before b, the function returns -1. This comparison is based on the color property.

If you need to handle cases where the colors are the same, you can include additional comparisons for secondary properties. For example:

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

This updated callback function first compares the color values, and if they are the same, it compares the size values to determine the order.

By using the sort() method with a custom callback function, you can easily sort an array of objects by a specific property value in JavaScript.

Tags: JavaScript, sorting, array of objects, property value sorting