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?

2
  • you can pass a custom sorting logic as a callback method Commented May 30, 2013 at 8:35
  • "will not sort properly" - maybe your definition of "properly" is wrong :-) Commented May 30, 2013 at 8:46

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

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.