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
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)
The output is correct, but the explanation is not. If the method returns < 0, a comes before b.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With