Js reduce to get the count of the objects
Hi Team,
I'm trying to get the count/frequency/Groupby of an array of objects. Using reduce I'm getting only one key and it's count using below code. However, I'd like to get the whole object with the frequency/count added to the object. Any idea on how to modify the below code to acheive this?
var data = [{
title: 'monk',
rating: 2,
price: 199
}, {
title: 'monk',
rating: 2,
price: 199
}, {
title: 'Gods Vs Geeks',
rating: 2,
price: 199
}];
var result2 = data.reduce(function(r, e) {
r[e.title]= (r[e.title] || 0) + 1;
return r;
}, {});
console.log(result2)
Result: {monk: 2, Gods Vs Geeks: 1}
Below is the format in which I want to get the data:
[{
title: 'monk',
rating: 2,
price: 199,
count: 2},
{
title: 'Gods Vs Geeks',
rating: 2,
price: 199,
count:1
}]