Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

300
Visualizações
Why does the sort() method does't work as expected with an array of strings?

I'm experimenting with the sort() method in JavaScript. The documentation says the return value should be > 0 to sort b before a. I have the following code to reverse an array of strings, and have the return value as a positive integer, which I think should sort the array in the reverse order:

let nums = ["x", "y", "z"];
nums.sort((a, b) => 1); // returning a positive number to sort b before a
console.log(nums)

However, when I execute the code, the output is:

[ 'x', 'y', 'z' ] // not reversed at all

But the code does give me the expected value - [ 'z', 'y', 'x' ] - when I set the return value to a negative number. Is there an explanation for this? Am I doing something wrong?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here you are not conditionally check out a and b which is greater or lesser. Returning 1 will evaluate first parameter from sort((a, b) is greater. Which returns you exact same array.

You better compare those to value inside sort callback function and depending on value return 1 or -1.

This will result ascending order.

let nums = ["x", "y", "z"];
nums.sort((a, b) => a > b ? 1 : -1);
console.log(nums)

Toggle return value to get descending order.

let nums = ["x", "y", "z"];
nums.sort((a, b) => a > b ? -1 : 1);
console.log(nums)

about 4 years ago · Juan Pablo Isaza Relatório

0

That happens because the callback of sort method, takes two params but they do not correspond as one would think to first second third...etc... elements but on the contrary, a is the second element, b is the first one, so when it says that a number greater than 1 places b ahead of a that's what it does:

const nums = ['x', 'y', 'z'];

nums.sort((a, b) => {
  console.log(a,b)  // yx -zy
});

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda