Array.prototype.reduce() 原理探索

流程图

在这里插入图片描述

语法

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

callback的四个参数

accumulator 累计器
currentValue 当前值
currentIndex 当前索引
array 数组

initialValue

initialValue为初始值,最为callback函数第一个作用的值

方法执行的顺序

提供的reducer函数(升序执行),将其结果汇总为单个返回值。数组或者类数组队尾先执行

案例一:累加方法

没有initialValue: accumulator的初始值是源数组的第一个元素,currentValue源数组的第二个元素
  const array1 = [1, 2, 3, 4]
    // 累加
    const reducer = (accumulator, currentValue,currentIndex,array) => {
      console.log("accumulator", accumulator)
      console.log("currentValue", currentValue)
      console.log("currentIndex", currentIndex)
      console.log("array", array)
     return accumulator + currentValue
    }
    console.log(array1.reduce(reducer))
打印无initalValue的结果

在这里插入图片描述

有initialValue: accumulator初始值为initialValue,currentValue取源数组或者源类数组的第一个值
 const array1 = [1, 2, 3, 4]
    // 累加
    const reducer = (accumulator, currentValue,currentIndex,array) => {
      console.log("accumulator", accumulator)
      console.log("currentValue", currentValue)
      console.log("currentIndex", currentIndex)
      console.log("array", array)
     return accumulator + currentValue
    }
    // console.log(array1.reduce(reducer))
    console.log(array1.reduce(reducer,7))
打印有initialValue结果

在这里插入图片描述

使用场景

场景一:累加对象数组的值
注意事项:必须设置initialValue以便可以让每一个元素可以通过reduce函数

比如使用在统计数量综合

   const numberOfSchool = [
      {
        number:20
      },
      {
        number: 30
      },
      {
        number: 40
      }
    ]
   const number = numberOfSchool.reduce((accumulator, currentValue)=>{
      // 此时accumulator 初始值为0
      return accumulator + currentValue.number
    },0)
    console.log("累加对象", number)
打印累加对象数组的值结果

在这里插入图片描述

场景二:二堆数组转换为一堆
const concatSeries= [[0, 1], [2, 3], [4, 5]].reduce(
      ( accumulator, currentValue ) => accumulator.concat(currentValue),
      []
     );
    console.log(concatSeries)
打印二堆数组转换为一堆结果

在这里插入图片描述

场景三:计算数组中每个元素出现的次数
const countedNames = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'].reduce((allNames, name)=> { 
      if (name in allNames) {
        allNames[name]++;
      }
      else {
        allNames[name] = 1;
      }
      return allNames;
    }, {});
    console.log(countedNames)
打印计算数组中每个元素出现的次数结果

在这里插入图片描述

场景四:按属性对object分类
const people = [
      { name: 'Alice', age: 21 },
      { name: 'Max', age: 20 },
      { name: 'Jane', age: 20 }
    ];
    const groupBy = (objectArray, property) =>{
      return objectArray.reduce( (acc, obj)=> {
        let key = obj[property];
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(obj);
        return acc;
      }, {});
    }
    console.log(groupBy(people, 'age'))
打印按属性对object分类结果

在这里插入图片描述

场景五: 数组去重
const myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
    const myOrderedArray = myArray.reduce((accumulator, currentValue)=> {
      if (accumulator.indexOf(currentValue) === -1) {
        accumulator.push(currentValue);
      }
      return accumulator
    }, [])
    
    console.log(myOrderedArray);
打印 数组去重结果

在这里插入图片描述

场景六:使用扩展运算符和initialValue绑定包含在对象数组中的数组及功能性管道
// 把第一个的返回值传递到下一个
    function f1(arg) {
      console.log("f1", arg)
      return arg
    }
    function f2(arg) {
      console.log("f2", arg)
      return arg
    }
    function f3(arg) {
      console.log("f3", arg)
      return arg
    }
    // 把三个函数聚合成为同一个
    function compose(...funcs) {
      console.log('...funcs', ...funcs)
      console.log('funcs', typeof funcs)
      // funcs是一个类数组
      if (funcs.length === 0) {
        // 返回一个函数,函数的返回值当前传递进去的参数
        return arg => arg
      }
      if (funcs.length === 1) {
        return funcs[0]
      }
      return funcs.reduce((a, b) => (...args) => {
        // 返回的是依旧是函数
        console.log('...args', args)
        return a(b(...args))
      });
    }
    /*
     f1,f2,f3 通过三点运算符将三个参数聚合成为一个arguments
     es6三点运算符可以展开数组或者类数组的对象
    */
    let dispatch = compose(f1, f2, f3)
    console.log(dispatch("abc"));
打印 使用扩展运算符和initialValue绑定包含在对象数组中的数组及功能性管道结果

在这里插入图片描述

react中的redux就是使用了Array.prototype.reduce() 原理相类似的reducer方法就行处理

资源链接

Array.prototype.reduce()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值