My difficulty here could be my mathematical illiteracy, but I was trying to sort some numbers in a JavaScript array and this is the solution I found online. It does indeed w
I am trying to answer your "It does indeed work BUT Why?"
Here is the syntax of the sort method in javascript. Note that the compareFunction is optional.
array.sort([compareFunction]);
When compareFunction is not provided:
When compareFunction is not provided, the default mode of sorting is followed wherein the elements of the array are converted into strings and than compared according to the UTF 16 code unit values and the elements are sorted in ascending order by default.
e.g. For string values, it follows simple UTF 16 code order. like "Banana" appears before "Cat"
for numbers, they first gets converted into strings and then compared according to UTF 16 code oder. So, 80 and 9 gets converted to strings "80" and "9" respectively and "80" comes before "9" according to the UTF 16 order.
When compareFunction is provided:
When compareFunction is provided, then the function takes over the sorting process and all the non-undefined elements gets sorted based on the return value of compareFunction according to the following logic.
If the compareFunction(a,b) returns negative value, a comes first by getting lower index than b.
If compareFunction(1,b) returns zero then both get the same index and hence do not change place respect to each other but both gets sorted with all other elements.
If compareFunction(a,b) returns positive value, a gets higher index than b and hence a comes after b.
The example you provided, uses a trick to decide each numbers comparative weightage in terms of its numeric value by subtracting each pair of numbers from the array.