对象值的总和数组

时间:2019-08-28 10:19:01

标签: javascript ecmascript-6 reduce

我需要对对象数组中相似“值”的值求和。

示例输入

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

预期产量

arrayOutput = [
{_id: "Week 1", count: 10},
{_id: "Week 2", count: 15},
{_id: "Week 3", count: 17}
]

我已尝试关注但未按预期工作

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

1 个答案:

答案 0 :(得分:1)

您不需要两个循环,只需使用reduceMap

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