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

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

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