Subscribe

JavaScript Sort Array of Objects by Value

โœ๏ธ

Guide to learn how to sort an array of objects based on a value, like a price. See the code examples in the Codepen!

31 May, 2020 ยท 3 min read

Have you ever had an array of objects and needed to sort them based on a specific value? This is an issue everyone will run into very often.

In our JavaScript example, we will look at a price list. Then we will sort the array by price.

If you are looking to randomly shuffle an array, read this article.

JavaScript Sort Array of Objects

Letโ€™s start with the following array of objects:

const products = [
  {
    color: 'white',
    price: 10,
    name: 'Basic T-shirt',
  },
  {
    color: 'red',
    price: 5,
    name: 'Cheap T-shirt',
  },
  {
    color: 'black',
    price: 50,
    name: 'Exclusive T-shirt',
  },
];

So, seeing this array, we already have two options for sorting it:

  1. we can sort based on color
  2. we sort by price

How do we now sort the array based on the price values?

Sort Array by Color

We can use the sort manipulator for Arrays.

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

As you can see, a straightforward sorting function. It will sort based on color and replace the values until itโ€™s done. You can think of this function as a manual if...else loop, but then all done for you.

Sort Array by Price

As for the price, we can sort the array with the following code:

products.sort((a, b) => (a.price > b.price ? 1 : -1));

Sorting on the second parameter

So letโ€™s say we want to sort on color, but if the color is the same, then we want to sort on price:

const productsPrice = [
  {
    color: 'white',
    price: 10,
    name: 'Basic T-shirt',
  },
  {
    color: 'white',
    price: 5,
    name: 'Cheap T-shirt',
  },
  {
    color: 'black',
    price: 50,
    name: 'Exclusive T-shirt',
  },
];

productsPrice.sort((a, b) =>
  a.color > b.color
    ? 1
    : a.color === b.color
    ? a.price > b.price
      ? 1
      : -1
    : -1
);

So the same setup, but we use the callback function to check if the color is the same. We then need to check on the price as well!

See the code examples in this Codepen

You can have a play with the following Codepen.

See the Pen JavaScript Sort Array of Objects by Value by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and letโ€™s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Removing all vowels with JavaScript

3 Dec, 2022 ยท 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 ยท 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter