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

100
Visualizações
Behind the scenes of Javascript sort comparison
const arr = [3, 89, 1, 120, 23];
console.log(arr.sort((a, b) => a - b));

The code above sorts the array. However, how does sort know that a = current index and that b = next index??? We never specify to sort what they are and to what they're equal to.

And after that, how does .sort figure out that the returned value from that anonymous arrow function means that the value need to be moved? Example: [1, 2]

sort((a, b) => a - b))
sort((1, 2) => 1 - 2))
sort((1, 2) => -1))
sort(-1));

See? How does .sort know what to do with -1?

I've been Googling and YouTubing for the past 2 hours and can't find the answer... :(

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

0

However, how does sort know that a = current index and that b = next index?

No, a is current value, b is next value.
The sort function you see is not just run once, it runs again and again, depending on which length your array has.
In your case, in the first run, a equals 3 and b equals 89. And the second run, a equals 3, b equals 1.

The sort function is work for an array of strings, so if you need to sort an array of strings, just use array.sort()
Compare function is required when you need to sort a numeric array.
If not, it gets the wrong result: "25" is bigger than "100", because "2" is bigger than "1".

Compare function just return three kinds of number:

  1. Negative number (-1,-2,...): it means a less than b
  2. Zero (0): it means a equals b
  3. Positive number (1,2,3..): it means a greater than b

So, you can more clearly return inside the Compare function like this:

if(a === b)
    return 0;
if(a < b)
    return -1;
return 1;

But, simpler, you can a using a trick, you just need to return a-b to determine whether a is greater than b or not.

See more: JavaScript Sorting Arrays

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