javascript - 我想用 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。
解决方案
您可以在传递给 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);
显示这两个选项的工作小提琴。(打开开发者控制台查看输出)
推荐阅读
- scrapy - 处理多个链接时,scrapy-splash 并不总是成功
- php - 运行 composer 时出错需要 pusher/pusher-php-server
- python - 将文本文件中的键和值添加到字典
- reactjs - 部署后反应不显示图像
- groovy - 在 Jmeter Groovy 中读取请求 Cokkie
- python - 如何使用外键/多键编写测试 - Django
- reactjs - 使用 FormData 从 React 应用程序上传 Sailsjs 文件不起作用
- r - 如何从向量中获得概率密度函数?
- python - 如何对采用列表列平均值的熊猫数据框执行 groupby 操作?
- keycloak - 如何在访问令牌中指定特定于客户端的自定义属性