Sometimes, we want to sort objects by property values with JavaScript.
In this article, we’ll look at how to sort objects by property values with JavaScript.
How to sort objects by property values with JavaScript?
To sort objects by property values with JavaScript, we can use the array 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 sortedCars = cars.sort((a, b) => {
return a.speed - b.speed;
});
to call cars.sort
with a function that returns a.speed - b.speed
to sort the cars
entries by the speed
property value of each entry in ascending order.
Conclusion
To sort objects by property values with JavaScript, we can use the array sort
method.