9

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
Community
  • 1
  • 1
ehp
  • 2,495
  • 6
  • 29
  • 43

4 Answers4

8

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    I assume it's because `.sort()` has to work with any type of data by default, including mixed types. How would you sort `[2, "10", "25f" ]` ? – JJJ Aug 11 '12 at 12:33
  • Yes that's probably it; the generic function would have to check the whole array to see if it's all numbers in order to be smarter. – Pointy Aug 11 '12 at 12:33
4

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);
Sujay
  • 2,198
  • 23
  • 32
3
var x = [40,100,1,5,25,10];
x.sort(function(a,b){return a-b});
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
woot
  • 3,671
  • 4
  • 26
  • 39
1

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

MimiEAM
  • 2,505
  • 1
  • 26
  • 28