How to sort numbers correctly with Array.sort()?
JavascriptArraysSortingNumbersNumericJavascript Problem Overview
In multiple browsers, the following code doesn't sort the numbers correctly:
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
document.write(a.sort())
It returns 10,100,20,30,60
.
Anyone know why?
Javascript Solutions
Solution 1 - Javascript
a.sort(function(a,b){return a - b})
These can be confusing.... check this link out.
Solution 2 - Javascript
>I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?
You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
> array.sort([compareFunction]) >Parameters > >compareFunction > > Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.
In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:
13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return −1.
19. If Result(16) > Result(17), return 1.
20. Return +0.
Solution 3 - Javascript
The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:
var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });
Solution 4 - Javascript
You can use a sort function :
var myarray=[25, 8, 7, 41]
myarray.sort( function(a,b) { return a - b; } );
// 7 8 25 41
Look at http://www.javascriptkit.com/javatutors/arraysort.shtml
Solution 5 - Javascript
try this:
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)
document.write(a);
function Test(a,b)
{
return a > b ? true : false;
}