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]
}
{
    /**
     * Runs promises from array of functions that can return promises
     * in chained manner
     *
     * @param {array} arr - promise arr
     * @return {Object} promise object
     */
    function runPromiseInSequence(arr, input) {
      return arr.reduce(
        (promiseChain, currentFunction) => promiseChain.then(currentFunction),
        // 这里的Promise.resolve(input)相当于initialValue
        Promise.resolve(input)
      )
    }
    // promise function 1
    function p1(a) {
      return new Promise((resolve, reject) => {
          console.log(a);
        resolve(a * 5)
      })
    }
    // promise function 2
    function p2(a) {
      return new Promise((resolve, reject) => {
          console.log(a);
        resolve(a * 2)
      })
    }
    // function 3  - will be wrapped in a resolved promise by .then()
    function f3(a) {
       console.log(a);
     return a * 3
    }
    // promise function 4
    function p4(a) {
      return new Promise((resolve, reject) => {
          console.log(a);
        resolve(a * 4)
      })
    }
    const promiseArr = [p1, p2, f3, p4]
    runPromiseInSequence(promiseArr, 10)
      .then(console.log)   // 1200
}
{
    // Building-blocks to use for composition
    const double = x => x + x
    const triple = x => 3 * x
    const quadruple = x => 4 * x

    // Function composition enabling pipe functionality
    const pipe = (...functions) => input => functions.reduce(
        (acc, fn) => fn(acc),
        // 这里的input相当于initialValue
        input
    )

    // Composed functions for multiplication of specific values
    const multiply6 = pipe(double, triple)
    const multiply9 = pipe(triple, triple)
    const multiply16 = pipe(quadruple, quadruple)
    const multiply24 = pipe(double, triple, quadruple)

    // Usage
    multiply6(6)   // 36
    multiply9(9)   // 81
    multiply16(16) // 256
    multiply24(10) // 240

}
{
    if (!Array.prototype.mapUsingReduce) {
      Array.prototype.mapUsingReduce = function(callback, thisArg) {
        return this.reduce((mappedArray, currentValue, index, array)=> {
          mappedArray[index] = callback.call(thisArg, currentValue, index, array)
          return mappedArray
        }, [])
      }
    }

    [1, 2, , 3].mapUsingReduce(
      (currentValue, index, array) => currentValue + index + array.length
    ) // [5, 7, , 10]
}

eagle007
34 声望0 粉丝

« 上一篇
小知识大集合