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

108
Vistas
Sorting array of object in JavaScript

I have this array of objects with an n and an o property holding an integer.
And I want to sort it by ascending value of the n property, and if two elements have the same value of n, then I want to order them by ascending value of o.

I know that the right way of doing this would be:

const s = [
  { n: 0, o: 0 },
  { n: 2, o: 1 },
  { n: 3, o: 2 },
  { n: 7, o: 3 },
  { n: 4, o: 4 },
  { n: 8, o: 5 },
  { n: 2, o: 6 },
  { n: 0, o: 7 },
  { n: 3, o: 8 },
  { n: 4, o: 9 },
  { n: 8, o: 10 },
  { n: 7, o: 11 },
  { n: 3, o: 12 },
  { n: 3, o: 13 },
];

console.log(s.sort((a, b) => (a.n === b.n ? a.o - b.o : a.n - b.n)));

But since o is basically the index of an object in the array, I thought I could swap a.o - b.o with -1, that is: if a.n === b.n, then "sort a before b", meaning preserve the order between a and b.

But it tuns out that -1 would actually sort by descending value of o:

const s = [
  { n: 0, o: 0 },
  { n: 2, o: 1 },
  { n: 3, o: 2 },
  { n: 7, o: 3 },
  { n: 4, o: 4 },
  { n: 8, o: 5 },
  { n: 2, o: 6 },
  { n: 0, o: 7 },
  { n: 3, o: 8 },
  { n: 4, o: 9 },
  { n: 8, o: 10 },
  { n: 7, o: 11 },
  { n: 3, o: 12 },
  { n: 3, o: 13 },
];

console.log(s.sort((a, b) => (a.n === b.n ? -1 : a.n - b.n)));

While if I try 1 rather than -1 I get the sorting I wanted.

Why do I need to return a positive value to keep the order of the elements, when the docs say the opposite? And can I rely on this behaviour or do I have to return a.o - b.o instead of 1 to consistently get the order I want?

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