I am having trouble understanding why the following function sorts the string numerically (in the third section of the code) .
var myArray = [10, 44, 32, 100, 0, 44, 3, 4];
console.log(myArray.toString()); // 10, 44, 32, 100, 0, 44, 3, 4 --> unsorted
myArray.sort();
console.log(myArray.toString()); // 0,10,100,3,32,4,44,44 --> sorted like strings
// this is what confuses me:
myArray.sort(function (a, b) {
return a - b;
});
console.log(myArray.toString()); // 0,3,4,10,32,44,44,100 --> sorted numerically
Specifically:
How do
a
andb
get populated?Why is does subtracting
a - b
sort the numbers in numerical order?How do all the numbers get sorted into proper order if the function is only examining 2 numbers at a time? (i.e.
a
andb
)