Why Javascript Sort() Function Is Not Giving The Expected Output?
Solution 1:
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.
Solution 2:
According to MDN Array.sort
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.
So you should be doing something like:
function compareNumbers(a, b)
{
return a - b;
}
var x = [40,100,1,5,25,10];
x.sort(compareNumbers);
Solution 3:
var x = [40,100,1,5,25,10];
x.sort(function(a,b){return a-b});
Solution 4:
It does an alphabetical, ascending sorting (the 1 character is sorted.. 1,1_,1_,2,4_,5) as default and providing a compare function changes that behavior
More info can be found here : http://www.w3schools.com/jsref/jsref_sort.asp
Post a Comment for "Why Javascript Sort() Function Is Not Giving The Expected Output?"