代码之家  ›  专栏  ›  技术社区  ›  stone rock

如何使用reduce()(es6)计算合计?

  •  0
  • stone rock  · 技术社区  · 6 年前

    我有数据 season fielding 数组。 实战化 数组有3个参数 Catches ,请 Runouts ,请 Stumpings .我想计算总数 捕捉 ,请 树桩 ,请 耗尽 .

    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
        }
    ]
    

    我希望最终输出为以下对象:

    Catches -> 2+0+0+1+2 = 5
    Runouts -> 1+1+0+3+1 = 6
    Stumpings -> 1+1+0+1+2 =5
    

    我的尝试:

    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;
            }, {});
    

    我的代码不计算所需的输出并给出 NaN .

    2 回复  |  直到 6 年前
        1
  •  4
  •   CertainPerformance    6 年前

    迭代 条目 属于 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;
      }, {})
    );
        2
  •  2
  •   baao    6 年前

    可以使用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>