Back to Home
Arrays

How to Sort Arrays

Use .sort() with a compare function for proper sorting

Quick Answer (2024 ES6+ Way)

javascript
const numbers = [10, 5, 40, 25, 1000];
const sorted = [...numbers].sort((a, b) => a - b);
console.log(sorted); // [5, 10, 25, 40, 1000]

Live Example

javascript
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);

Common Variations

Sort Strings
javascript
const sorted = strings.sort((a, b) => 
  a.localeCompare(b)
);
Multi-Level Sort
javascript
const sorted = items.sort((a, b) => {
  if (a.category !== b.category) {
    return a.category.localeCompare(b.category);
  }
  return a.price - b.price;
});

❌ Don't Do This (Outdated Way)

Avoid sorting without compare function for numbers

javascript
// DON'T DO THIS
const sorted = numbers.sort();
// [1000, 10, 25, 40, 5] - wrong! Sorts as strings

Browser Support

Works in all modern browsers (ES5+)

#array#sort#order