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
- 1.sort() mutates the array; use [...arr] for immutable.
- 2.Comparator returns negative, zero, or positive.
- 3.a - b for numbers; localeCompare for strings.
Expected output
Sorted by age