0

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)
})
Dibish
  • 9,133
  • 22
  • 64
  • 106

1 Answers1

2

You don't need two loops, you can simply use reduce and Map

let 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}]


let final = array.reduce((op,inp) => {
  let {_id, count} = inp
  let obj = op.get(_id) || {_id,count:0}
  obj.count += count
  op.set(_id, obj)
  return op
},new Map())


console.log([...final.values()])
Code Maniac
  • 37,143
  • 5
  • 39
  • 60