If I were to run "[6,3,8,7,5,2,1,9,4,0].sort()" I get "[0,1,2,3,4,5,6,7,8,9]" as an output like you would expect. It sorts the numbers from smallest to largest. But if I were to run "[2,3,1,4e-20].sort()" I get "[1,2,3,4e-20]" as an output. Why does the ".sort()" function treat "4e-20" as larger than "3"? Even if you run "3>4e-20" you get "true" as an output, showing that JavaScript does realize that "4e-20" is an incredibly tiny number. But the sort function treats it as an incredibly larger number. Why is this? and is there some way I can change it, or do I just have to write my own function?
Asked
Active
Viewed 689 times
1
-
Please read over this sentence carefully: "Even if you run "3>4e-20" you get "true" as an output, showing that JavaScript does realize that "4e-20" is an incredibly tiny number." – IMSoP Jun 21 '14 at 19:08
-
possible duplicate of [arr.sort() does not sort integers correctly](http://stackoverflow.com/questions/1063007/arr-sort-does-not-sort-integers-correctly) (this also applies to non-integer numbers) – user2864740 Jun 21 '14 at 19:13
-
http://stackoverflow.com/questions/7000851/array-sort-doesnt-sort-numbers-correctly?lq=1 , http://stackoverflow.com/questions/1063007/arr-sort-does-not-sort-integers-correctly , http://stackoverflow.com/questions/11914665/why-javascript-sort-function-is-not-giving-the-expected-output?lq=1 – user2864740 Jun 21 '14 at 19:14
3 Answers
6
From MDN Array.sort:
"The default sort order is according to string Unicode code points."
It then goes on "[to] compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending":
function compareNumbers(a, b) {
return a - b;
}

user2864740
- 60,010
- 15
- 145
- 220

Kodlee Yin
- 1,089
- 5
- 10
4
You might want to do this:
[2, 3, 1, 4e-20].sort(function (a, b) {
return a - b;
});
That happens because (according to MDN) when no sorter function is provided, it uses an unicode string comparator.

Danilo Valente
- 11,270
- 8
- 53
- 67
4
Array.sort() in javascript does not sort by < and >, it instead does a lexical sort, which means it treats the numbers as strings and sorts them that way. This is what causes the longer 4e-20 to be sorted higher than the shorter and (lexically) lower 3.
While a - b
works, this is a theoretically faster comparison because it is branchless: (a > b) - (a < b)

reem
- 7,186
- 4
- 20
- 30