-1

I am trying this:-

[231, 907, 1246, 1203, 1305, 484, 709, 1220, 616, 1200].sort();

and output is this:-

[1200, 1203, 1220, 1246, 1305, 231, 484, 616, 709, 907]

where typeof of arrays first element I checked is number.

any Idea why its not working ?

Arun Tyagi
  • 2,206
  • 5
  • 24
  • 37
  • 2
    Please search harder for answer on SO. The default sort order is string-based. –  Apr 15 '16 at 17:55
  • 1
    From the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), `var scores = [1, 10, 2, 21]; scores.sort(); // [1, 10, 2, 21]` – Rayon Apr 15 '16 at 17:56
  • 1
    `[231, 907, 1246, 1203, 1305, 484, 709, 1220, 616, 1200].sort(function compareNumbers(a, b) { return b-a; });` – Rayon Apr 15 '16 at 17:57

3 Answers3

5

Use a callback for numbers like

function numSortDesc(a, b) {
    return b - a;
}

var data = [231, 907, 1246, 1203, 1305, 484, 709, 1220, 616, 1200];

data.sort(numSortDesc);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
4

From MDN, the prototypical inherited method for sorting on Array is:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

So the sort is correct, and you have omitted the comparator function. Add a comparator function to sort based on what you want (in this case, any anonymous callback function for numeric ascending or descending order will do, i.e.:)

function(a, b) {
   if (a == b) {
       return 0;
   }
   return (a > b) ? 1 : -1; //Depending on your desired sort order
}
q.Then
  • 2,743
  • 1
  • 21
  • 31
3

This happens because .sort() will alphabetize. If you want to sort by number value you need to specify the time of sort as such:

document.write([231, 907, 1246, 1203, 1305, 484, 709, 1220, 616, 1200].sort((a,b) => b-a));

b - a will sort the array descending, and a - b ascending

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

brso05
  • 13,142
  • 2
  • 21
  • 40
Sergio Prada
  • 161
  • 1
  • 10