The function .sort
should always return numbers. Negative, positive or zero. That is, this function is badly drawn.
To specification is clear:
Returns to Negative value if x < y, zero if x = y, or a Positive value if x > y
However, and 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 is basically a condition that gives true
if the number is odd .sort
will give priority to the results that give false
thus solved the beginning of the result 2,4,6,8,10
and then the rest.
If we put together a console.log
to understand why the odd ones are reversed:
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 is in second place, and in the next iteration this previous odd index N is pushed right by the odd noo.
Only by strengthening Sergio’s answer: it is not possible to order stone, paper and scissors. Computational ordering requires
a > b > c
, necessarilya > c
. But that doesn’t apply to stone, paper and scissors, wherepedra > tesoura > papel > pedra
– Jefferson Quesado