Why doesn't the javascript sort () function give the expected result?

Possible duplicate:
does sorting not work with integers?
How to sort a room in the method of sorting javascript
Array.sort () does not sort numbers correct

the code:

var x = [40,100,1,5,25,10];
x.sort();

conclusion:

1,10,100,25,40,5

My expected result:

1,5,10,25,40,100
+5
source share
4 answers

The JavaScript Array function, .sort()by default, converts array elements to strings before performing comparisons.

You can override this:

x.sort(function(e1, e2) { return e1 - e2; });

(A missed function should return a number that is negative, zero or positive, depending on whether the first element is less than, equal to, or greater than the second.)

I have never seen the rationale for this odd aspect of language.

+6

MDN Array.sort

compareFunction , ( "" " ", ) . , "80" "9" , 9 80.

, - :

function compareNumbers(a, b)
{
  return a - b;
}
var x = [40,100,1,5,25,10];
x.sort(compareNumbers);
+4
var x = [40,100,1,5,25,10];
x.sort(function(a,b){return a-b});
+3

, ( 1 .. 1,1_, 1_, 2,4_, 5)

More information can be found here: http://www.w3schools.com/jsref/jsref_sort.asp

+1
source

All Articles