Home > Mobile >  How do I count the number of unique elements in an array of objects using the object property?
How do I count the number of unique elements in an array of objects using the object property?

Time:11-22

I have an array that looks like this:

let arr = [
    {'option1':1},{'option1':1},{'option1':1},
    {'option1':2},{'option1':2},
    {'option1':3},
    {'option2':1},{'option2':1}
]

I need to iterate through the array and count the occurrences of each element with the same property to be displayed like this:

   option1:{
            1:3,
            2:2,
            3:1,
           },
   option2:{
            1:2,
           }

Basically saying that option1 with a property of 1 has 3 counts, option1 with a property of 2 has 2 counts, option1 with a property of 3 has 1 count and so on.

CodePudding user response:

this way...

let arr = 
  [ { option1: 1 }, { option1: 1 }, { option1: 1 } 
  , { option1: 2 }, { option1: 2 } 
  , { option1: 3 } 
  , { option2: 1 }, { option2: 1 } 
  ] 

let obj = arr.reduce((r,o)=>
  {
  let [name,num] = Object.entries(o)[0] 
  if (!r[name]) r[name] = {}
  if (!r[name][num]) r[name][num] = 1
  else               r[name][num]  
  return r
  },{})

console.log( obj )
.as-console-wrapper { max-height: 100% !important; top: 0 }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related