首页 > 解决方案 > 我想用 Reduce 汇总对象数组中的某些值

问题描述

我只想总结使用 Reduce 方法的专业和精英玩家。

data = [ 
  { name: 'pro', players: 3 },
  { name: 'free', players: 8 },
  { name: 'elite', players: 1 } 
  ]

我知道 Reduce 返回 12 的玩家总数,但我只想返回专业和精英玩家的总和。

到目前为止我的减少方法。

const players = data.reduce((accum, cur) => {
   return accum + cur.players;
}, 0);

这将返回 12。

但是,我希望它仅通过仅添加专业和精英玩家来返回 4。

标签: javascriptecmascript-6

解决方案


您可以在传递给 reduce 方法的函数中添加一个 if 语句,如果满足条件,它只会添加到累加器中,否则只返回累加器......

const players = data.reduce((accum, cur) => {
    if (cur.name === "pro" || cur.name === "elite") {
        return accum + cur.players;
    }
    return accum;
}, 0);

或者你可以过滤列表然后减少它......

const players = data
    .filter(item => item.name === "pro" || item.name === "elite")
    .reduce((accum, cur) => accum + cur.players, 0);

reduce 方法filter 方法的文档都很棒。

显示这两个选项的工作小提琴。(打开开发者控制台查看输出)


推荐阅读