Why can `sort()` put numbers in an unexpected order?
Quick answer
JavaScript’s default array sort() compares elements as strings, not as numbers, so values such as 100 can come before 25. Pass a numeric comparison function, such as (a, b) => a - b, for ascending numeric order. sort() also changes the array it sorts, so copy the array first if you need to preserve its original order. [S1]
The question, the details, the next step.
A practical checklist
Check whether your call supplies a comparison function.
For ascending numeric order, use
(a, b) => a - b.Decide whether sorting should reorder the existing array.
If the original order must remain, copy the array before sorting.
Check the resulting array against the order your task requires.
A few more useful answers
Why does `100` appear before `25` with plain `sort()`?
Without a comparison function, JavaScript converts array elements to strings and compares them as text-like values, not by numeric size. [S1]
Will assigning the result of `sort()` preserve my original array?
No. sort() changes the array it sorts and returns that same array. Sort a copy if you need to preserve the original order. [S1]
What comparator should I use for ascending numeric order?
Use (a, b) => a - b, as in values.sort((a, b) => a - b). [S1]
Sources
References used for this guide.
- [S1] Array.prototype.sort() — JavaScript | MDN developer.mozilla.org · Checked
