关于javascript:漂亮的reduce写法

6次阅读

共计 2479 个字符,预计需要花费 7 分钟才能阅读完成。

reduce 实现递归查找属性 https://blog.csdn.net/lihefei…

let peoples = {
    zhangsan: {
        name: '张三',
        height: 170,
        child: {name: '张小小'},
    },
    lisi: {
        name: '李四',
        weight: 200,
        wife: {name: '杨玉环'},
    },
    wagnwu: {
        name: '王五',
        age: 21,
    },
};
let str = 'lisi.wife.name';
let propArr = str.split('.');

let result = propArr.reduce((prev,next)=>{return prev[next] ? prev[next] : null;
}, peoples);

console.log(result); // 杨玉环 

应用 reduce() 办法解决树形构造数据 https://www.cnblogs.com/dhui/…

array.reduce(function(prev, cur, index, array){...}, init);

回调函数中的参数:

prev 必须。示意调用回调时的返回值,或者初始值 init。

cur 必须。示意以后元素。

index 可选。示意以后元素的索引。

array 示意原数组。

init 可选。初始值,作为第一次调用回调函数的第一个参数。
其中罕用参数:prev 和 cur

留神:回调函数第一次执行时,prev 和 cur 的取值有两种状况:如果调用 reduce() 时提供了初始值 init,prev 取 init 值,cur 取数组中的第一个值,此时索引从 0 开始;如果没有提供初始值 init,则 prev 取数组中的第一个值,cur 取数组中的第二个值,此时索引从 1 开始。

// 利用 && 符号来判断 + 执行,几乎丑陋极了
{const arr = ['ab', 'v', 'd', 'ab', 'h', 'e', 'dc', 'e', 'e', 'f']
    const newArr = arr.reduce(function(prev, cur){!prev.includes(cur) && prev.push(cur)
        return prev
    }, [])
    console.log(newArr) // ["ab", "v", "d", "h", "e", "dc", "f"]
}
{// 初始值设为 {},用 reduce 满足统计次数性能
    let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']

    let countedNames = names.reduce((allNames, name)=> {if (name in allNames) {allNames[name]++
      }
      else {allNames[name] = 1
      }
      return allNames
    }, {}) 
    console.log(countedNames);
    // countedNames is:
    // {'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1}
}
    // 利用 reduce 实现属性值分组
    let people = [{ name: 'Alice', age: 21},
      {name: 'Max', age: 20},
      {name: 'Jane', age: 20}
    ];

    function groupBy(objectArray, property) {return objectArray.reduce((acc, obj)=> {let key = obj[property]
        if (!acc[key]) {acc[key] = []}
        acc[key].push(obj)
        return acc
      }, {})
    }

    let groupedPeople = groupBy(people, 'age');
    console.log(groupedPeople);
    // groupedPeople is:
    // { 
    //   20: [//     { name: 'Max', age: 20}, 
    //     {name: 'Jane', age: 20}
    //   ], 
    //   21: [{name: 'Alice', age: 21}] 
    // }
}
{
    // 返回对象中的属性为数组的状况
    // friends - an array of objects 
    // where object field "books" is a list of favorite books 
    let friends = [{
      name: 'Anna',
      books: ['Bible', 'Harry Potter'],
      age: 21
    }, {
      name: 'Bob',
      books: ['War and peace', 'Romeo and Juliet'],
      age: 26
    }, {
      name: 'Alice',
      books: ['The Lord of the Rings', 'The Shining'],
      age: 18
    }]

    // allbooks - list which will contain all friends' books +  
    // additional list contained in initialValue
    let allbooks = friends.reduce(function(accumulator, currentValue) {return [...accumulator, ...currentValue.books]
    }, [])

    // allbooks = [
    //   'Bible', 'Harry Potter', 'War and peace', 
    //   'Romeo and Juliet', 'The Lord of the Rings',
    //   'The Shining'
    // ]
}
{const numbers = [-5, 6, 2, 0,];
    const doubledPositiveNumbers = numbers.reduce((accumulator, currentValue) => {const doubled = (num)=>{accumulator.push(num*2); 
        }
        // 判断,满足条件即执行函数
        currentValue > 0 && doubled(currentValue);
          return accumulator;
    }, []);
    console.log(doubledPositiveNumbers); // [12, 4]
}
正文完
 0