JavaScript – Sort an array of objects by property value

To sort an array of objects by property, you can use sort() method of JavaScript. You can pass comparison function that compares two objects based on the property you want to sort by.

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 20 }
];
let sortedUsers = users.sort((a, b) => a.age-b.age);
console.log(sortedUsers);

Output

[{
  age: 20,
  name: "Charlie"
}, {
  age: 25,
  name: "Alice"
}, {
  age: 30,
  name: "Bob"
}]

To sort by name, you can use localeCompare() method, for ex

const users = [
  { name: "Charlie", age: 25 },
  { name: "Alice", age: 30 },
  { name: "Bob", age: 20 }
];
let sortedUsers = users.sort((a, b) => a.name.localeCompare(b.name));
console.log(sortedUsers);

Output

[{
  age: 30,
  name: "Alice"
}, {
  age: 20,
  name: "Bob"
}, {
  age: 25,
  name: "Charlie"
}]

Similar Reads