Use .sort() with a compare function for proper sorting
const numbers = [10, 5, 40, 25, 1000];
const sorted = [...numbers].sort((a, b) => a - b);
console.log(sorted); // [5, 10, 25, 40, 1000]const users = [
{ name: 'Charlie', age: 35 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
// Sort by age (ascending)
const byAge = [...users].sort((a, b) => a.age - b.age);
console.log(byAge.map(u => u.name));
// Sort by name (alphabetical)
const byName = [...users].sort((a, b) =>
a.name.localeCompare(b.name)
);
console.log(byName.map(u => u.name));
// Sort descending
const desc = [...numbers].sort((a, b) => b - a);const sorted = strings.sort((a, b) =>
a.localeCompare(b)
);const sorted = items.sort((a, b) => {
if (a.category !== b.category) {
return a.category.localeCompare(b.category);
}
return a.price - b.price;
});Avoid sorting without compare function for numbers
// DON'T DO THIS
const sorted = numbers.sort();
// [1000, 10, 25, 40, 5] - wrong! Sorts as strings✓ Works in all modern browsers (ES5+)