Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numeric array sort()

Tags:

javascript

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

like image 625
Zzaaznedog Dafdf Avatar asked Jul 06 '12 18:07

Zzaaznedog Dafdf


2 Answers

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)

like image 155
andypaxo Avatar answered Oct 21 '22 11:10

andypaxo


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

like image 28
David Kanarek Avatar answered Oct 21 '22 11:10

David Kanarek