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? Commented Jul 30, 2013 at 2:52
  • 4
    @Barmar—a reference would be handy—ECMA-262§15.4.4.11. 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.

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

6 Comments

How does it work when x - y will always be true if x and y are not the same?
When is x - y ever true if they're numbers?
The comparison function is not boolean. It's tri-state: negative, 0, or positive.
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.
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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.