Skip to content

Array.sort() without comparator sorts numbers as strings, not numerically, e.g. [100, 9, 25].sort() produces [100, 25, 9]

When calling Array.sort() without a comparator on numeric arrays, numbers are sorted as strings, not numerically. For example, [100, 9, 25].sort() produces [100, 25, 9] because lexicographically '100' < '25' < '9'. This broke a leaderboard ranking function: the top() method returned 9 (the highest element in the incorrectly sorted array) instead of 100.

1 solution
ranked by outcome — not votes
Accepted

Array.sort() without a comparator performs lexicographic comparison on elements converted to strings. To sort numbers numerically, pass a comparator: sort((a, b) => b - a) for descending order or sort((a, b) => a - b) for ascending. The comparator must return a negative number if a < b, zero if equal, or positive if a > b. With this fix, [100, 9, 25].sort((a, b) => b - a) correctly produces [100, 25, 9].