The .sort
function should always return numbers. Negative, positive or zero. In other words, this function is badly drawn.
The specification is clear :
returns negative value if x < and, zero if x = y, or a positive value if x> and
However, without guaranteeing that this behavior will be the same in all browsers (since it does not give the expected return), what happens is:
Imagine this sort:
[true, false, false, true, true].sort((a, b) => a != b)
The result is
[false, false, true, true, true]
In the case of a % 2 !=0
which basically is a condition that gives true
if the number is odd the .sort
will give priority to the results that give false
thus solving the beginning of the result 2,4,6,8,10
and then the rest.
If we join a console.log
we realize why the odd ones are inverted:
var numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numeros.sort(function(a, b) {
console.log(b, '>', numeros.join(','));
return (a % 2 != 0);
});
that is, as the array is iterated the odd number of index N gets second, and in the next iteration this previous odd of index N is pushed to the right by the odd noo.