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

136
Vistas
Sorting Array Elements with .sort()

I'd like to understand intrinsically, how does array.sort() method works? Like, under the hood, what happens? Is this a kind of data structure that works really fast? Is there a for.each hidden somewhere in the code because I can't figure out what happens with a and b

let numbers = [ 0, 1, 10, 2, 20, 3, 30 ];
numbers.sort((a,b) =>{
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});

console.log(numbers);

Plus, how can the above code become this:

let numbers = [ 0, 1, 10, 2, 20, 3, 30 ];
numbers.sort((a, b) => a - b);
console.log(numbers);

#EDIT1 Ok, I got that if the result of a-b is negative a get first position, otherwise are swapped, if they are equal they stay in position. My question is: does Javascript engine sort every time till there is no more swapping?

Let's pretend I have  arr = [1,20,10,5,2] 
1st round: a=1 b=20 result  [1,20,10,5,2]
2nd round: a=10 b=20 result [1,10,20,5,2]
3rd round: a=20 b=5 result  [1,10,5,20,2]
end of this cycle becomes   [1,10,5,2,20] 

Array is not fully sorted. Does it start all over again? Where and how does the engine know that the sorting has finished?

about 4 years ago · Juan Pablo Isaza
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