Given a sample JSON array of objects, like this....
[
{
"firstName": "Bob",
"lastName": "Smith",
"city": "Preston",
"st": "Florida",
"age": 15
},
{
"firstName": "Tom",
"lastName": "Jones",
"city": "Springfield",
"st": "Illinois",
"age": 34
},
{
"firstName": "Mary",
"lastName": "Hart",
"city": "Miami",
"st": "Florida",
"age": 22
},
{
"firstName": "Jenny",
"lastName": "Dixon",
"city": "Palm City",
"st": "Florida",
"age": 26
}
]
What is the best way to get the number of occurrences based on the groupings of a particular property? So, let's say I want to produce a JSON object that has each unique state ("st") and the number of occurrences....
[
{
"st": "Illinois",
"count": 1
},
{
"st": "Florida",
"count": 3
}
]
I can do it manually using a for-let, looping through the array, tracking the values as I loop, etc. But I'm sure there's a more efficient way using ES6. Can you please help me out? Thanks.
Object.entries(data.reduce((o, d) => ({...o, [d.st]: (o[d.st] || 0) + 1 }), {})).map(([st,count]) => ({ st, count }))const results = Object.values(data.reduce((obj, item) => { obj[item.st] = obj[item.st] = { st: item.st : count: 0 }; obj[item.st].count++; return obj }, {}));