美文网首页
es6数组方法reduce()方法

es6数组方法reduce()方法

作者: 暖lily | 来源:发表于2020-11-20 13:48 被阅读0次

    含义

    reduce() 函数将数组元素进行组合,例如求和,取最大值 第一个参数是指定函数,第二个参数是传递给函数的初始值;函数会返回一个简化后的值,
    t7 = t.reduce(function(x,y){return x+y},0)//10 依次进行简化值,将t每项遍历完返回最后的值

    初始数据

    var objects = [
      {name:'group1', usedCount: 2, color:'red'},
      {name:'group1', usedCount: 1, color:'blue'},
      {name:'group1', usedCount: 1, color:'orange'},
      {name:'group2', usedCount: 2, color:'blue'},
      {name:'group2', usedCount: 2, color:'red'},
      {name:'group3', usedCount: 1, color:'red'},
      {name:'group3', usedCount: 4, color:'red'}
    ]
    

    期待结果

     [
       {name:'group1', usedCount: 4, color:['red','blue','orange']},
       {name:'group2', usedCount: 4, color:['blue','red']},
       {name:'group3', usedCount: 5, color:['red']}
    ]
    

    reduce方法使用

    var result = objects.reduce(function(x,y){
        //x0为初始值,相当于第一个x
    var x0 = x.find(x0 => x0.name === y.name);
    if(x0){
        x0.usedCount = x0.usedCount+y.usedCount;
        if(x0.color.indexOf(y.color) == -1){
            x0.color.push(y.color)
        }
        
    }else{
        var xn = {
            name:y.name,
            usedCount:y.usedCount,
            color:[y.color]
        }
        x.push(xn);
    }
    return x;
    },[])
    

    相关文章

      网友评论

          本文标题:es6数组方法reduce()方法

          本文链接:https://www.haomeiwen.com/subject/loudiktx.html