-1

There must be something very simple wrong with this code, but it doesn't sort. Why is that?

  $(document).ready(function () {
            var topArray = [];
            topArray.push(1000);
            topArray.push(298);
            topArray.push(2000);
         topArray.sort();
            alert(topArray[0] + "," + topArray[1] + ", " + topArray[2]);
        })
Gideon Isaac
  • 395
  • 4
  • 17

3 Answers3

0

You need to sort the numbers by numbers, not by string, which is the default sorting.

Description

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.

topArray.sort(function (a, b) {
    return a - b;
});
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In default Array#sort method sorts based on string comparison instead, implement custom sort function.

topArray.sort(function(a, b){ return a - b; });


From MDN docs :

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

add sorting options to it, as noted in here: http://www.w3schools.com/jsref/jsref_sort.asp

$(document).ready(function () {
        var topArray = [];
        topArray.push(1000);
        topArray.push(298);
        topArray.push(2000);
     topArray.sort((function(a, b){return a-b}));
        alert(topArray[0] + "," + topArray[1] + ", " + topArray[2]);
    })
elicohenator
  • 747
  • 6
  • 17