Sort a JavaScript array of named objects by numeric named property

Viewed 19

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.

1 Answers

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

Related