Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda