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

146
Visualizações
Array sort with primary and secondary value

Is there a way to sort an array of objects using a primary and secondary value? What i mean is an array like this:

[
    { primary: 0, secondary: 'a' },
    { primary: 1, secondary: 'a' },
    { primary: 1, secondary: 'b' },
    { primary: 0, secondary: 'b' }
]

will be sorted using the primary value, so the first two objects with the primary value of 0 come first then the values of 1 come second, and then it will be again sorted by the secondary value and it will result in the array becoming

[
    { primary: 0, secondary: 'a' },
    { primary: 0, secondary: 'b' },
    { primary: 1, secondary: 'a' },
    { primary: 1, secondary: 'b' }
]

im havent really touched the Array.sort() before so im trying to find out how to do this, any help will be appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use Array#sort.

Comparison would be by primary first (numeric), or by secondary if equal (string using String#localeCompare)

const arr = [ { primary: 0, secondary: 'a' }, { primary: 1, secondary: 'a' }, { primary: 1, secondary: 'b' }, { primary: 0, secondary: 'b' } ];

const res = arr.sort((a, b) => 
  a.primary - b.primary || a.secondary.localeCompare(b.secondary)
);

console.log(res);

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