loading...
Cover image for JavaScript Sort Array of Objects by Value

JavaScript Sort Array of Objects by Value

dailydevtips1 profile image Daily Dev Tips Originally published at daily-dev-tips.com ・2 min read

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, imagine a price list of any table list.

JavaScript Sort Array of Objects by Value

Let's start with the following array of objects:

var 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 list, we already have a quick two options, we want to sort based on color and price.

How do we now sort this based on the values?

We can use the sort manipulator for Arrays.

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

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

As for the price we can do the following:

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, we want to sort on price.

var 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 are using the callback function to check if the color is the same, we then need to check on price as well!

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

Posted on May 31 by:

dailydevtips1 profile

Daily Dev Tips

@dailydevtips1

I write daily development tips to contribute to the development community!

Discussion

markdown guide