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
The JavaScript Array
.sort()function by default converts the array elements to strings before making comparisons.You can override that:
(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.