Group Array Of Objects By Value And Get Count Of The Groups
I have an array objects [ { group: 1 }, { group: 2 ], { group: 2 } ] I want to get the count of distinct groups by property value 'group', expecting the result of 2 How to do this
Solution 1:
You just need to store counts in your aggregator for each key using reduce.
const data = [ { 'group': 1 }, { 'group': 2 }, { 'group': 2 } ]
const groups = data.reduce((agg, curr)=>{
if(agg[curr.group]){
agg[curr.group] += 1
}
else{
agg[curr.group] = 1
}
return agg
},{})
console.log(groups)
Solution 2:
i'm not sure that i understand your question right. If you want group your object by value equals to 2, using filter will be useful
const obj = [ { group: 1 }, { group: 2 }, { group: 2 }, { group: 2 } ]
// new array with group value equals to 2const countGroup = () => {
return obj.filter(it => it.group === 2)
}
// count how many group with value equals to 2const countGroupCount = () => {
return obj.filter(it => it.group === 2)
}
console.log(countGroup())
console.log(countGroupCount())
Post a Comment for "Group Array Of Objects By Value And Get Count Of The Groups"