2

I find this really intriguing.

When- var x = [1, 50, 2, 4, 2, 2, 88, 9, 10, 22, 40];

Then x.sort(); will not sort properly

When var x = ["dog","apple","zebra","cow"]; , x.sort(); will sort properly.

what is the proper function to sort them in one call?

Ishank
  • 2,860
  • 32
  • 43

3 Answers3

3

You must define a custom sort and pass it as a callback to sort(). The callback is passed two arguments.

For numeric sorting:

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

The default Array.sort() converts each element to string and sorts lexicographically.

c.P.u1
  • 16,664
  • 6
  • 46
  • 41
1

As per ECMAScript 15.4.4.11 Array.prototype.sort(comparefn), sorting is done alphabetically by default meaning that 22 comes before 4. It's actually a great deal more complicated in the document but that's basically what it boils down to.

If you want to sort them numerically, you need to provide your own comparison function, such as:

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

The function just has to return a negative number if a < b, zero if they're equal or a positive number if a > b.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

you should just pass in your own sorting method and sort them however you like. You can treat them as strings or numbers or anything else, as well as sort them in ascending or descending order. Additionally, you can pass in objects and sort those objects based on specific members. It's very rare that the generic sort() method will be useful by default.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236