Sort Array of Objects

Sort an array by object properties with Array.sort().

Code

JavaScript
const users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Carol", age: 35 }
];

// By age ascending
users.sort((a, b) => a.age - b.age);

// By name (string)
users.sort((a, b) => a.name.localeCompare(b.name));

// Immutable sort (new array)
const sorted = [...users].sort((a, b) => a.age - b.age);

Line-by-line explanation

Expected output

Sorted by age

Related snippets

Related DuskTools