Lessons · JavaScript · sorting numbers as text
sort() sorts as text
Without a comparator, sort converts everything to strings: [10, 9, 1] becomes [1, 10, 9].
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Every table that ever showed 10 before 9 forgot this. It is the most common JavaScript sorting bug.
How to think about it
Are these numbers? Always pass a comparator for numbers: (a, b) => a - b. For strings use localeCompare. Prefer toSorted() to keep the original.
Worked example
[10, 9, 1].sort()[1, 10, 9]: text order.
[10, 9, 1].sort((a, b) => a - b)[1, 9, 10].
names.sort((a, b) => a.localeCompare(b))Alphabetical, accents handled.
Your turn
Sort scores highest first.
scores.sort((a, b) => );
Solve one with the tests running
The trap
sort mutates the array and returns it, so const s = arr.sort() changes arr too.
Practise sorting numbers as text on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.