Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!