Use Array.prototype.sort() with a custom comparator function to sort objects by any property.
Sort by Number
Subtract: (a, b) => a.age - b.age for ascending, or b.age - a.age for descending.
Sort by String
Use localeCompare() for correct alphabetical ordering (handles accents, locale differences).
Sort by Date
Convert to Date objects or timestamps and subtract.
Note
.sort() mutates the original array. Use [...arr].sort() to sort a copy.
Example
const users = [
{ name: 'Charlie', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
// Sort by age ascending
const byAge = [...users].sort((a, b) => a.age - b.age);
// Sort by name alphabetically
const byName = [...users].sort((a, b) => a.name.localeCompare(b.name));
// Sort by date
const posts = [
{ title: 'First', date: '2024-01-15' },
{ title: 'Second', date: '2024-03-20' },
];
const byDate = [...posts].sort((a, b) => new Date(a.date) - new Date(b.date));