iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Array Sort

sort() orders an array in place. Default sort is lexicographic — almost never what you want for numbers. Pass a comparator.

The comparator rule

For two items a and b, return:

  • Negative → a comes before b.
  • Positive → b comes before a.
  • Zero → keep their relative order (modern engines are stable).

Recipes

JS
// Ascending numeric
nums.sort((a, b) => a - b);

// Descending numeric
nums.sort((a, b) => b - a);

// By a field
users.sort((a, b) => a.age - b.age);

// Strings (locale-aware, handles accents)
names.sort((a, b) => a.localeCompare(b));

// Random shuffle (rough — not cryptographic)
arr.sort(() => Math.random() - 0.5);

// Multi-key — by role, then by name
users.sort((a, b) =>
  a.role.localeCompare(b.role) || a.name.localeCompare(b.name)
);

Non-mutating modern variants

JS
// Returns a new sorted array — original untouched
const sortedAsc = nums.toSorted((a, b) => a - b);
const reversed  = arr.toReversed();

Why default sort surprises people

JS
[10, 2, 1, 20].sort();           // [1, 10, 2, 20] — string compare
[10, 2, 1, 20].sort((a, b) => a - b);   // [1, 2, 10, 20] ✓
Tip: sort mutates. If the array is React state or shared, sort a copy: [...arr].sort(cmp) or use toSorted.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Array Sort!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Sort numbers ascending (numerical).

nums.sort((a, b) => a b);

Test yourself

Q1. Default `[10, 2, 1, 20].sort()` returns…
Q2. Ascending numeric sort uses…
Q3. `Array.prototype.sort` is…

Discussion

Loading…