0

When I want to sort an array, using sort() function , it is giving an alphabetically sorted array. Eg.

var a=[9,10,1];
a.sort();

I'm getting a = [1,10,9]

So, as per the suggestions I used another function

function sortfunction(x, y){
    return (x - y) //causes an array to be sorted numerically and ascending
}

and then used

a.sort(sortfunction);

to get the right result.

Can anyone explain in detail, how this works?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Lonely
  • 613
  • 3
  • 6
  • 14
  • 4
    Isn't it explained in detail in the Javascript specification? – Barmar Jul 30 '13 at 02:52
  • 4
    @Barmar—a reference would be handy—[ECMA-262§15.4.4.11](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11). – RobG Jul 30 '13 at 02:54

1 Answers1

3

The first version fails as they're compared like they're strings ("9" is greater than "10"), known as a lexicographic sort.

The custom comparator function is called with a and b being members of the array.

Depending on what is returned, the members are shifted. If 0 is returned, the members are considered equivalent, if a negative number, then a is less than b and the inverse if it's a positive number.

If you want to visualise this, you can always log a and b to the console and observe how they're compared (and note how there is never any redundant comparisons made).

This is all backed by a sorting algorithm, which is left up to the implementation to choose. Chrome, for example, uses different algorithms depending on the type of members.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984