Categories
JavaScript Answers

How to sort objects by property values with JavaScript?

Spread the love

To sort objects by property values with JavaScript, we use the sort method.

For instance, we write

const cars = [
  {
    name: "Honda",
    speed: 80,
  },
  {
    name: "BMW",
    speed: 180,
  },
  {
    name: "Trabi",
    speed: 40,
  },
  {
    name: "Ferrari",
    speed: 200,
  },
];

const soreted = cars.sort((a, b) => {
  return a.speed - b.speed;
});

to call cars.sort with a callback that sorts the objects in the cars array by the speed property value in ascending order.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *