我想用Reduce总结对象数组中的某些值

时间:2019-11-21 01:02:23

标签: javascript ecmascript-6

我只想使用Reduce方法总结职业球员和精英球员。

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

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

到目前为止,我的reduce方法。

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

这将返回12。

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

2 个答案:

答案 0 :(得分:2)

您可以将if语句添加到传递给reduce方法的函数中,该条件仅在满足条件时才添加到累加器中,否则只需返回累加器...

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 methodfilter method的文档都很棒。

Working fiddle显示两个选项。 (打开开发人员控制台以查看输出)

答案 1 :(得分:0)

这是解构的另一种方式。


const totalPaidPlayers = data.filter(({ name }) => name !== 'free')
.reduce((total, { players }) => (total + players), 0)

或者这样。完全相同,但是在箭头功能之后返回。


  const totalPaidPlayers = data.filter(({ name }) => {
    return name !== 'free'
  }).reduce((total, {players}) => {
    return total + players
  }, 0)