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

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

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 Denunciar

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 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