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?

2
  • 4
    Isn't it explained in detail in the Javascript specification?
    – Barmar
    Commented Jul 30, 2013 at 2:52
  • 4
    @Barmar—a reference would be handy—ECMA-262§15.4.4.11.
    – RobG
    Commented Jul 30, 2013 at 2:54

1 Answer 1

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.

6
  • How does it work when x - y will always be true if x and y are not the same? Commented Jul 30, 2013 at 2:54
  • When is x - y ever true if they're numbers?
    – alex
    Commented Jul 30, 2013 at 2:55
  • 3
    The comparison function is not boolean. It's tri-state: negative, 0, or positive.
    – Barmar
    Commented Jul 30, 2013 at 2:56
  • Oh .sort depends on negative or positive values. I thought it receives a Boolean instead. I totally forgot about it and I just read the spec. Commented Jul 30, 2013 at 2:58
  • so , sortfunction return either 0.+ve or -ve. and these are passed as a argument to a.sort(), what will be the first argument to a.sort()? will that be difference of first two elements of the array?
    – Lonely
    Commented Jul 30, 2013 at 3:01

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.