After this lesson you can sort a list of numbers, words or objects in the order you want, and you will know why the plain sort() call sometimes gives answers that look wrong.
The surprise in the default sort
Try it before reading the explanation.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
log([10, 9, 1, 100].sort().join(", "));
log(["banana", "Apple", "cherry"].sort().join(", "));
</script>The numbers come out as 1, 10, 100, 9 and the words as Apple, banana, cherry (it happens to look right, but capital letters sort before lowercase ones, so "Zebra" would come before "apple"). The reason: with no argument, sort converts every item to a string and compares them character by character. As text, "10" begins with "1", which is less than "9". For anything except simple lowercase words, you should pass a compare function.
The compare function
sort takes an optional function that receives two items, a and b, and returns a number:
- negative:
ashould come first, - zero: keep them as they are (they tie),
- positive:
bshould come first.
For numbers, subtraction does exactly this:
const nums = [10, 9, 1, 100];
nums.sort((a, b) => a - b);
console.log(nums); // [ 1, 9, 10, 100 ] ascending
nums.sort((a, b) => b - a);
console.log(nums); // [ 100, 10, 9, 1 ] descendingIf a is smaller than b, a - b is negative, so a goes first. Flip the subtraction to reverse the order.
A frequent beginner version is (a, b) => a > b. It returns true or false, which become 1 and 0, never a negative number, and the result is unreliable. Always return a number.
In place, with a return value
sort changes the array you call it on and also returns that same array. That is easy to forget:
const original = [3, 1, 2];
const sorted = original.sort((a, b) => a - b);
console.log(original); // [ 1, 2, 3 ], it was changed
console.log(sorted === original); // true, same arrayIf you need to keep the original order, sort a copy: [...original].sort(...). Modern JavaScript (ES2023) also has toSorted, which does that for you: original.toSorted((a, b) => a - b) returns a new sorted array and leaves original alone. It is available in current browsers and Node 20 and later.
The sort is also stable in modern engines: items that compare as equal keep their original relative order. That is useful for the multi-step sorts below.
Sorting text
For words, use localeCompare. It returns a negative, zero or positive number, so it slots straight into sort, and it understands letters in different languages and (by default) does not put every capital before every lowercase letter.
const names = ["zoe", "Asha", "ben", "Émile"];
names.sort((a, b) => a.localeCompare(b));
console.log(names); // [ 'Asha', 'ben', 'Émile', 'zoe' ]Results of localeCompare can vary slightly by language settings and environment. For a specific language pass it as the second argument, for example a.localeCompare(b, "de"). You can add { numeric: true } as the third argument so "item2" sorts before "item10".
Sorting objects
Compare one property. The same rule applies: return a number.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const people = [
{ name: "Chen", age: 31 },
{ name: "Asha", age: 25 },
{ name: "Ben", age: 31 },
];
// By age, oldest first; ties broken by name
const sorted = people.toSorted((a, b) => b.age - a.age || a.name.localeCompare(b.name));
log(sorted.map(p => p.name + " " + p.age).join("\n"));
</script>The output is Ben 31, Chen 31, Asha 25. The || trick works because when two ages are equal the subtraction gives 0, which is falsy, so JavaScript moves on to the name comparison. This reads left to right as "by age, and if tied, by name".
Other order tricks
reverse()flips an array in place (toReversed()gives a copy).- To shuffle, do not use
sort(() => Math.random() - 0.5). It gives a biased order. Learn the Fisher-Yates algorithm instead. - To sort dates, subtract them:
(a, b) => a.date - b.dateworks forDateobjects because they convert to numbers. See dates and time. - Missing values (
undefined) are always placed at the end bysortand never reach your compare function.
Common mistakes
- Sorting numbers without a compare function, getting
[1, 10, 100, 9]. - Forgetting that
sortmutates, and wondering why another part of the program sees a different order. - Returning a boolean from the compare function.
- Sorting a
constarray and expecting an error.constdoes not stop in-place changes. - Trusting the default for mixed-case text, which puts capitals first.
Exercise
Sort [5, 25, 100, 1] in ascending order without changing the original array. Then sort the words ["pear", "fig", "banana", "kiwi"] by length, shortest first, and show both results.
Show one possible answer
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const nums = [5, 25, 100, 1];
const ascending = [...nums].sort((a, b) => a - b);
log("sorted:", ascending.join(", "));
log("original:", nums.join(", "));
const words = ["pear", "fig", "banana", "kiwi"];
words.sort((a, b) => a.length - b.length);
log(words.join(", "));
</script>Next: objects.
Key points
- sort changes the array in place and also returns it; toSorted returns a sorted copy.
- Without a compare function, sort converts items to strings, so 10 comes before 2.
- A compare function receives two items and returns a negative number, zero or a positive number.
- For numbers use (a, b) => a - b for ascending and (a, b) => b - a for descending.
- Use localeCompare to sort text, and compare one property to sort objects.