The code works to sort out number values, but I'm confused how comparison function works in a sort() method. When comparing the array value '3' and '9'.
Shouldn't the value 3 be passed through the parameter 'a' in sortNum(a,b) and 9 be passed through parameter 'b'? But console.log() returns the '9' for 'a' and '3' for 'b'
let num = [3, 9, 1, 6]
function sortNum(a,b){
console.log(a); // returns 9...
console.log(b); // returns 3...
return a-b;
}
num.sort(sortNum);
console.log(num); //returns sorted numbers [1, 3, 6, 9]
I was expecting console.log(a) to have 3 instead of 9 since the num arrays first value is 3
There are many different sorting algorithms. The JS specification doesn't require that an implementation use any particular one. Some implementations use multiple (e.g. optimising for short or long arrays depending on how many items are in the array).
The callback function you pass to sort()
needs to be consistent and return less than zero, zero or more than zero depending on which (if either) of the two arguments is required to be forward of the other).
If 1 should be sorted before 2, then 2 should be sorted after 1 and it doesn't matter which way the sort algorithm passes them into the callback function.
Different implementations might feed them into the algorithm different ways around.