sort() changes the array, and sorts as text
By default sort() converts items to strings and compares them as text. That produces a surprising result for numbers.
const numbers = [10, 9, 1, 100];
console.log(numbers.sort()); // → [1, 10, 100, 9]
“100” comes before “9” because the character “1” comes before “9”. It also mutates the original array.
The compare function
Pass a function (a, b) => ... that returns:
- a negative number if
ashould come first, - a positive number if
bshould come first, 0if they are equal.
For numbers, subtraction does exactly this.
const numbers = [10, 9, 1, 100];
numbers.sort((a, b) => a - b);
console.log(numbers); // → [1, 9, 10, 100]
numbers.sort((a, b) => b - a);
console.log(numbers); // → [100, 10, 9, 1]
Sorting objects
const users = [
{ name: "Sam", age: 31 },
{ name: "Maya", age: 25 },
{ name: "Arjun", age: 28 }
];
users.sort((a, b) => a.age - b.age);
console.log(users.map(u => u.name)); // → ["Maya", "Arjun", "Sam"]
Sorting text for people
Use localeCompare, which understands language rules (accents, case).
const names = ["Émile", "zoe", "Adam", "bob"];
names.sort((a, b) => a.localeCompare(b));
console.log(names); // → ["Adam", "bob", "Émile", "zoe"]
A plain a < b comparison would put every capital letter before every lowercase letter.
reverse()
reverse() flips the order in place.
const letters = ["a", "b", "c"];
letters.reverse();
console.log(letters); // → ["c", "b", "a"]
Keep the original: copy first
Because both methods mutate, make a copy when you need the original order:
const original = [3, 1, 2];
const sorted = [...original].sort((a, b) => a - b);
console.log(sorted); // → [1, 2, 3]
console.log(original); // → [3, 1, 2]
Newer browsers have toSorted() and toReversed() that do this for you, see Changing Arrays Without Mutating Them.