Possible Duplicate:
sort not working with integers?
How to sort number in javascript sort method
Array.sort() doesn't sort numbers correctly
Code:
var x = [40,100,1,5,25,10];
x.sort();
output:
1,10,100,25,40,5
My expected output:
1,5,10,25,40,100
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.
A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.
sort() returns the reference to the same array The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
sort() Return Value The sort() method doesn't return any value.
The JavaScript Array .sort()
function by default converts the array elements to strings before making comparisons.
You can override that:
x.sort(function(e1, e2) { return e1 - e2; });
(The function passed should return a number that's negative, zero, or positive, according to whether the first element is less than, equal to, or greater than the second.)
I've never seen a rationale for this odd aspect of the language.
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