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

98
Visualizações
How do I sort objects in arrays that don't always have a property?

Here is an example of my array:

const database = [
  { name: item1, errors: true },
  { name: item2, factors: { rank: 1 } },
  { name: item3, factors: { rank: 2 } },
  { name: item2, errors: true },
];

Here is what I want:

const sorted_database = [
  { name: item3, factors: { rank: 2 } },
  { name: item2, factors: { rank: 1 } },
  { name: item1, errors: true },
  { name: item2, errors: true },
];

While this part of the post might not be necessary, to clarify, I want the array to be sorted with the rank descending and if it's undefined to remain in some random order below. I do however, need to keep all of the data. I have tried just using sort, and got an error for undefined property. I then tried making two different sets, but for some reason they rarely matched each other. Looking for an elegant solution someone perhaps knows to this that I haven't yet learned.

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

0

You could look for factors first and then sort by rank.

const
    database = [{ name: 'item1', errors: true }, { name: 'item2', factors: { rank: 1 } }, { name: 'item3', factors: { rank: 2 } }, { name: 'item2', errors: true }];

database.sort((a, b) =>
    !a.factors - !b.factors ||
     b.factors?.rank - a.factors?.rank
);

console.log(database);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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