How does the sort method work?

6

I'm starting to learn javascript and while looking for examples of sort I came across the following code:

var numeros = [1,2,3,4,5,6,7,8,9,10];
numeros.sort(function (a, b) {
   return (a % 2 !=0);
});

console.log (numeros);

The console output looks like this:

(10) [2,4,6,8,10,9,7,5,3,1]

I just wanted to understand what sort did to get this result.

    
asked by anonymous 22.10.2017 / 16:56

2 answers

6

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.

    
22.10.2017 / 17:10
5

The function sort of Array sorts the array based on the past function. The documentation says that if in the function the returned value is less than 0 then the value a goes to the start, otherwise a goes to the end.

In your case you happen to be testing if a is odd with:

return (a % 2 !=0);

That will give false if it is even and true if it is odd, which is putting the pairs first. To respect the expected numeric return for the sort function, you can turn it into:

return (a % 2);

That will return a positive number if it is odd or 0 if it is even:

var numeros = [1,2,3,4,5,6,7,8,9,10];
numeros.sort(function (a, b) {
   return (a % 2);
});

console.log(numeros);

This function is however more useful for comparing objects, in which you can indicate the comparison rules of these, which in turn force the ordering:

const pessoas = [
  { nome : "Claudio", idade : 22 },
  { nome : "Marta", idade : 19 },
  { nome : "Roberto", idade : 38 },
  { nome : "Jessica", idade : 27 }
];

let pessoasPorNome = pessoas.sort(function(a,b){
  return a.nome > b.nome;
});

console.log("Pessoas por nome:",pessoasPorNome);

let pessoasPorIdade = pessoas.sort(function(a,b){
  return a.idade > b.idade;
});

console.log("Pessoas por idade:",pessoasPorIdade);

Documentation for the sort function

    
22.10.2017 / 17:06