[英]How to calculate total using reduce() (ES6)?
I have data which has season
and fielding
array. 我有
season
和fielding
排列的数据。 fielding
array has 3 parameters Catches
, Runouts
, Stumpings
. fielding
阵列具有3个参数Catches
, Runouts
, Stumpings
。 I want to calculate total Catches
, Stumpings
, Runouts
. 我要计算总
Catches
, Stumpings
, Runouts
。
var data = [
{
season:2015,
fielding:{Catches:2, Runouts:1, Stumpings:1
},
{
season:2016,
fielding:{Catches:0, Runouts:1, Stumpings:1
},
{
season:2016,
fielding:{Catches:0, Runouts:0, Stumpings:0
},
{
season:2017,
fielding:{Catches:1, Runouts:3, Stumpings:1
},
{
season:2017,
fielding:{Catches:2, Runouts:1, Stumpings:2
}
]
I want final output as object as follows: 我想要最终输出作为对象,如下所示:
Catches -> 2+0+0+1+2 = 5
Runouts -> 1+1+0+3+1 = 6
Stumpings -> 1+1+0+1+2 =5
What I tried : 我试过了
let dismissals = data.reduce( (a,{season, fielding}) => {
if(!a[fielding.Catches]){
a[fielding.Catches] = {};
}else if(a[fielding.Runouts]){
a[fielding.Runouts] = {};
}else if(a[fielding.Stumpings]){
a[fielding.Stumpings] = {};
}else{
a[fielding.Stumpings] += 1;
a[fielding.Runouts] += 1;
a[fielding.Catches] += 1;
}
return a;
}, {});
My code does not calculate required output and gives NaN
. 我的代码未计算所需的输出,而是提供了
NaN
。
Iterate over the entries of fielding
, and add the value to the [key] in the accumulator (defaulting to 0
if the key doesn't exist yet): 遍历
fielding
的条目 ,并将值添加到累加器的[key]中(如果该键尚不存在,则默认为0
):
var data=[{season:2015,fielding:{Catches:2,Runouts:1,Stumpings:1}},{season:2016,fielding:{Catches:0,Runouts:1,Stumpings:1}},{season:2016,fielding:{Catches:0,Runouts:0,Stumpings:0}},{season:2017,fielding:{Catches:1,Runouts:3,Stumpings:1}},{season:2017,fielding:{Catches:2,Runouts:1,Stumpings:2}}]; console.log( data.reduce((a, { fielding }) => { Object.entries(fielding).forEach(([key, val]) => { if (key !== '_id') a[key] = (a[key] || 0) + val; }); return a; }, {}) );
You could use reduce and loop fielding
's Object.keys 您可以使用reduce和loop
fielding
的Object.keys
const res = data.reduce((a, {fielding}) => Object.keys(fielding).forEach(f => a[f] = (a[f] || 0) + fielding[f]) || a , Object.create(null)); console.log(res);
<script> var data = [ { season:2015, fielding:{Catches:2, Runouts:1, Stumpings:1} }, { season:2016, fielding:{Catches:0, Runouts:1, Stumpings:1} }, { season:2016, fielding:{Catches:0, Runouts:0, Stumpings:0} }, { season:2017, fielding:{Catches:1, Runouts:3, Stumpings:1} }, { season:2017, fielding:{Catches:2, Runouts:1, Stumpings:2} } ]; </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.