10

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?

1
  • Because it is treating above array as array of string Commented Mar 12, 2018 at 7:18

5 Answers 5

13

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
});
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

Comments

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);

Comments

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.