How to easily sort a Javascript array of objects by property
February 16, 2020
The Javascript sort() method is pretty simple to use:
let products = ['t-shirt', 'jeans', 'coat']
products.sort() // result = coat, jeans, t-shirt
At it's most basic, it will convert the array values into strings, and sort them in ascending order alphabetically.
But what if your array contains objects like this:
let products = [
{name: 't-shirt', price: 15.95},
{name: 'jeans', price: 35.95},
{name: 'coat', price: 25.95}
]
When you have an array of objects in Javascript, we often want to sort the array based on a property value, such as our price.
To do this, we can pass into the sort() method an optional "compare" function, which will compare 2 elements in our array at a time.
The names we give to the 2 elements are up to us, a basic example using a and b looks like this:
let numbers = [1, 5, 3, 8,9,0]
numbers.sort((a,b) => a-b)
// result = 0, 1, 3, 5, 8, 9
This basic example compares 2 elements at a time, then returns the results of each one.
As an example, if the first comparison was 1-5, this would result in a negative value (-4), and sort 1 as a lower value than 5. Repeat this for the rest of the array, and we now have a sorted array by comparison.
We want to compare the price property however, and going back to our products example, we can do it like this:
let products = [
{name: 't-shirt', price: 15.95},
{name: 'jeans', price: 35.95},
{name: 'coat', price: 25.95}
]
products.sort((a, b) => (a.price > b.price) ? -1 : 1)
// result:
0: {name: "jeans", price: 35.95}
1: {name: "coat", price: 25.95}
2: {name: "t-shirt", price: 15.95}
Here we are again passing in a function to the sort method, but this time, we are using the Javascript ternary operator to compare the price properties.
Depending on the result, the values will receive either a value of 1 or -1, resulting in the prices sorted in descending order.
We can reverse this to ascending order by switching the negative and positive values:
products.sort((a, b) => (a.price > b.price) ? 1 : -1)
// result:
0: {name: "t-shirt", price: 15.95}
1: {name: "coat", price: 25.95}
2: {name: "jeans", price: 35.95}