1

I have faced with strange sorting result in Javascript for numeric arrays. For example result of sorting [1,2,10,20,100,200]:

> [1, 2, 10, 20, 100, 200].sort()
[ 1, 10, 100, 2, 20, 200 ]

Why it's happening?

It seems what the array sort cannot be used for sorting numeric arrays directly?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Denis Kreshikhin
  • 8,856
  • 9
  • 52
  • 84
  • 1
    Yep. That's how it is defined in the specification: http://es5.github.io/#x15.4.4.11. – Felix Kling Nov 02 '13 at 08:01
  • 1
    possible duplicate of [sort not working with integers?](http://stackoverflow.com/questions/1063007/sort-not-working-with-integers) – darthmaim Nov 02 '13 at 08:06

5 Answers5

13

From the MDN documentation:

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.

(or see the relevant part of the EMCAScript specification, hat tip to Felix Kling for digging up the reference)

If you want to do a numeric sort, then pass a compare function:

[1, 2, 10, 20, 100, 200].sort(function (a,b) { return a-b; });
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Sorting arrays in JavaScript is done via the method array.sort(). Calling sort() by itself simply sorts the array in alphabetical order, for example:

var array=[40, 6, 300]; 
array.sort();

Array now becomes [300,40,6], the function is going to sort only by first number.

In this case to sort write a function:

Array.sort(function(number1, number2){
    return number1-number2;  
}) 

Array now becomes [6,40,300].

piyush das
  • 11
  • 3
0

array.sort only sorts strings. To sort numbers use this:

[1, 2, 10, 20, 100, 200].sort(function(a,b) { return a-b });
darthmaim
  • 4,970
  • 1
  • 27
  • 40
0

Try this for numeric sorting:

[ 1, 10, 100, 2, 20, 200 ].sort(function(a,b){return a-b})
jorel
  • 808
  • 7
  • 15
0

The sort() method calls the String() casting function on every item and then compares the strings to determine the correct order. This occurs even if all items in an array are numbers. Try this way:

function compare(value1, value2) { 
    if (value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {
    return 0; 
    }
}
[ 1, 10, 100, 2, 20, 200 ].sort(compare);
Nik Terentyev
  • 2,270
  • 3
  • 16
  • 23