This seems like a simple sort, yet JavaScript is giving an incorrect result.
Am I doing something wrong or is this a language quirk?
[5, 10, 1].sort();
[ 1, 10, 5 ]
This is because sort() needs a callback comparator, and when sort() is used without one, String() acts as the default callback. This is our callback function that will help sort the numbers in the correct and ascending order.
sort(Object[]) is based on the TimSort algorithm, giving us a time complexity of O(n log(n)).
JavaScript Array sort() The sort() sorts the elements as strings in alphabetical and ascending order.
To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.
Javascript sorts alphabetically. This means that "10" is lower than "5", because "1" is lower than "5".
To sort numerical values you need to pass in numerical comparator like this:
function sorter(a, b) {
if (a < b) return -1; // any negative number works
if (a > b) return 1; // any positive number works
return 0; // equal values MUST yield zero
}
[1,10, 5].sort(sorter);
Or you can cheat by passing simpler function:
function sorter(a, b){
return a - b;
}
[1, 10, 5].sort(sorter);
Logic behind this shorter function is that comparator must return x>0 if a > b
, x<0 if a < b
and zero if a is equal to b
. So in case you have
a=1 b=5
a-b will yield negative(-4) number meaning b is larger than a
a=5 b=1
a-b will yield positive number(4) meaning a is larger than b
a=3 b=3
a-b will yield 0 meaning they are equal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With