Reputation: 349
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?
Upvotes: 1
Views: 1059
Reputation: 7246
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)
Upvotes: 4
Reputation: 1089
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;
}
Upvotes: 6
Reputation: 11352
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.
Upvotes: 4