How to sort objects by property values with JavaScript?

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.