How to sort an array of objects by a property value in JavaScript
New Course Coming Soon:
Get Really Good at Git
Let's find out how to sort an array of objects by a property value in JavaScript!
Suppose you have an array of objects.
You might have this problem: how do you sort this array of objects by the value of a property?
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.
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 )
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X