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

81
Visualizações
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 Respostas
Responde à pergunta

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