7

We were going through the Array.prototype.sort() MDN documentation, where we saw an example: 

var array1 = [1, 2,3,4,5,6,7,8,9,10];
array1.sort();
console.log(array1);

So the expected output is

[1, 2, 3 , 4, 5, 6, 7, 8, 9, 10] 

But insted of this we got 

[1, 10, 2, 3, 4, 5, 6, 7, 8, 9]

Why isn’t it sort as we expected?

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
Alex Varghese
  • 2,000
  • 16
  • 17

5 Answers5

9

You need to use a sort function. By default sort uses alphabetic sorting instead of numeric.

array1.sort(function (a,b) {
    return a - b; // Ascending
});

array1.sort(function (a,b) {
    return b - a; // Descending
});
Sachin Singh
  • 898
  • 1
  • 8
  • 17
0

It is from the from the reference of This post

var numArray = [1, 2,3,4,5,6,7,8,9,10];
for (var i = 0; i < numArray.length; i++) {
    var target = numArray[i];
    for (var j = i - 1; j >= 0 && (numArray[j] > target); j--) {
        numArray[j+1] = numArray[j];
    }
    numArray[j+1] = target
}
console.log(numArray);
Nikhil Ghuse
  • 1,258
  • 14
  • 31
0
    function sorter(a, b) {
      if (a < b) return -1;  // any negative number works
      if (a > b) return 1;   // any positive number works
      return 0; // equal values MUST yield zero
    }

   [1, 2,3,4,5,6,7,8,9,10].sort(sorter);
DRastislav
  • 1,892
  • 3
  • 26
  • 40
0

Please use the following code:

var array1 = [1, 2,3,4,5,6,7,8,9,10];
array1.sort(function(a,b){
    return parseInt(a) > parseInt(b);
    }
  );
console.log(array1);
I. Ahmed
  • 2,438
  • 1
  • 12
  • 29
0

You can pass a function to sort method, For Asc sort :

array1.sort(function(a,b){return a>b?1:b>a?-1});
Rassoul
  • 174
  • 16