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)
})
0

1 Answer 1

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()])

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.