10

Is this part from the book "Learning PHP, MySql and Javascript by. Robin Nixon" wrong?

numbers = [7, 23, 6, 74];

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

output is 6,7,23,74

The book says:

If the anonymous function inside sort() returns a value greater than zero, the sort assumes a comes before b.

If the anonymous function inside sort() return a value less than zero, the sort assumes b comes before a.

The sort runs this function across all the values in the array to determine their order.

is this wrong? Because....

a here is 7
b here is 23

7 - 23 = -16 // a number less than zero. Book says it should b comes before a.

so the final output should be 74, 23, 7, 6

10
  • 1
    No, it's right: jsfiddle.net/cjD3v Commented Jul 6, 2012 at 18:27
  • 4
    You know, you could just: try it out. Like in the above jsfiddle Commented Jul 6, 2012 at 18:28
  • 1
    but the explanation from the book is that wrong?? Commented Jul 6, 2012 at 18:28
  • 1
    Yes, the explanation in the book is wrong. Commented Jul 6, 2012 at 18:29
  • 1
    Thats what im asking so the explanation from the book is wrong. Thanks guys. Commented Jul 6, 2012 at 18:30

2 Answers 2

5

It appears that it is wrong. From MDN:

If compareFunction(a, b) is less than 0, sort a to a lower index than b.

("Lower index" in this case would mean that a comes before b)

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

Comments

2

The output is correct, but the explanation is not. If the method returns < 0, a comes before b.

Comments

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.