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

82
Vistas
Sort a JavaScript array of named objects by numeric named property

I've seen multiple similar questions to this, but I can't figure out how to apply the proposed solutions to a slightly different data structure.

Here's an array of named objects that need to be sorted numerically by the property count:

const myArray = [
  {ABC:{label:'ABC', count:3}},
  {EFG:{label:'EFG', count:10}},
  {DEF:{label:'DEF', count:9}},
  {FGH:{label:'FGH', count:1}}
]

And the resulting array after sorting should be like this:

myArray = [
   {FGH:{label:'FGH', count:1}},
   {ABC:{label:'ABC', count:3}},
   {DEF:{label:'DEF', count:9}},
   {EFG:{label:'EFG', count:10}}
]

If the objects didn't have a name (ABC, DEF, etc) then the MDN web docs (along with multiple similar questions here) contain the solution for sorting such an array.

That is, consider a slightly different array of unnamed objects:

const myArray1 = [
  {label:'ABC', count:3},
  {label:'EFG', count:10},
  {label:'DEF', count:9},
  {label:'FGH', count:1}
]

This one-liner works: myArray1.sort((a, b) => a.count - b.count) to obtain:

myArray1 = [
  {label:'FGH', count:1},
  {label:'ABC', count:3},
  {label:'DEF', count:9},
  {label:'EFG', count:10}
]

I know a more complex function expression is necessary to handle this, but I just don't know the language well enough (yet) to figure it out.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Just take the first (and only) object value first before comparing.

const myArray = [
  {ABC:{label:'ABC', count:3}},
  {EFG:{label:'EFG', count:10}},
  {DEF:{label:'DEF', count:9}},
  {FGH:{label:'FGH', count:1}}
]

const getCount = obj => Object.values(obj)[0].count;
myArray.sort((a, b) => getCount(a) - getCount(b));
console.log(myArray);

about 4 years ago · Santiago Trujillo 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