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

109
Visualizações
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 à 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