如何在 JavaScript 中计算数组的总和
我想在 JavaScript 中计算数组数据的总和。
数组:
[
{
red_team: {
count: 2,
money: 3000,
},
blue_team: {
count: 10,
money: 100000,
},
},
{
red_team: {
count: 1,
money: 1000,
},
blue_team: {
count: 100,
money: 200000,
},
}
]
预期结果:
{
red_team: {
count: 3,
money: 4000,
},
blue_team: {
count: 110,
money: 300000,
},
}
注意:red_team
& blue_team
是一个枚举。
我怎样才能计算它?
I want to calculate sum of array data in JavaScript.
Array :
[
{
red_team: {
count: 2,
money: 3000,
},
blue_team: {
count: 10,
money: 100000,
},
},
{
red_team: {
count: 1,
money: 1000,
},
blue_team: {
count: 100,
money: 200000,
},
}
]
Expected Result :
{
red_team: {
count: 3,
money: 4000,
},
blue_team: {
count: 110,
money: 300000,
},
}
Note : red_team
& blue_team
is an Enum.
how can I calculate it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将数组展开到 lodash 的
_.mergeWith()
中,并创建一个对数字求和的定制器,但对于所有其他类型返回undefined
,以便 lodash 能够处理所有其他情况:Spread the array into lodash's
_.mergeWith()
, and create a customizer that sums number, but returnsundefined
for all other types, so that lodash would handle all other cases:根据上面的评论,有无限种方法可以做到这一点。我刚刚想出了一个(诚然相当冗长)
详细的解决方案:
Per a comment above, an infinite ways of doing this. I just came up with one (rather verbose admittedly)
Verbose solution: