Sort by a number field

const users = [{ name: "Sam", age: 30 }, { name: "Ada", age: 22 }];
users.sort((a, b) => a.age - b.age);
// Ada (22), then Sam (30)

Subtracting gives a negative, zero, or positive number, which is exactly what sort expects. Swap to b.age - a.age for descending order.

Sort by a text field

users.sort((a, b) => a.name.localeCompare(b.name));
// Ada, then Sam

localeCompare handles letters, accents, and case correctly, which a plain subtraction cannot do for strings.

Avoid mutating the original array

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

sort changes the array in place. Spreading into a fresh array first keeps your original data untouched.

Common mistakes

  • Calling sort() with no compare function. It sorts by string order, so 10 lands before 2.
  • Forgetting that sort mutates. Copy with the spread operator if you need the original.
  • Returning a boolean instead of a number from the compare function.

Frequently asked questions

How do I sort descending?

Flip the operands: (a, b) => b.age - a.age for numbers, or b.name.localeCompare(a.name) for text.

Why is 10 sorted before 2?

Without a compare function, sort converts values to strings, so “10” comes before “2”. Always pass a numeric compare function for numbers.

Get comfortable with arrays and callbacks in our free JavaScript course.