I have a requirement to sum the values of similar 'value' in an array of object.
Sample input
array = [
{_id: "Week 1", count: 5},
{_id: "Week 2", count: 10},
{_id: "Week 1", count: 5},
{_id: "Week 3", count: 10},
{_id: "Week 3", count: 2},
{_id: "Week 2", count: 5},
{_id: "Week 3", count: 5}
]
Expected output
arrayOutput = [
{_id: "Week 1", count: 10},
{_id: "Week 2", count: 15},
{_id: "Week 3", count: 17}
]
I have tried following but not working as expected
final = [];
array.forEach(function (data) {
var val = array.reduce(function (previousValue, currentValue) {
console.log(previousValue)
return {
[data._id] : previousValue.count + currentValue.count,
}
});
final.push(val)
})