How to sort arrays in JavaScript correctly

· Category: JavaScript

Short answer

Array.prototype.sort sorts elements as strings by default. Always provide a comparator function for numeric, date, or object sorting.

Steps

  1. Sort numbers ascending: javascript [10, 2, 5].sort((a, b) => a - b);
  2. Sort strings case-insensitively: javascript ["banana", "Apple"].sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
  3. Sort objects by property: javascript users.sort((a, b) => a.age - b.age);
  4. Create a new sorted array without mutating the original: javascript const sorted = [...arr].sort((a, b) => a - b);

Tips

  • sort mutates the array in place; copy it first if immutability matters.
  • For stable sorting of equal elements, modern engines guarantee stability since ES2019.

Common issues

  • [10, 2, 5].sort() produces [10, 2, 5] because numbers are coerced to strings ("10" < "2").
  • Returning a boolean from the comparator instead of a number causes inconsistent ordering.