数组方法reduce

reduce() 方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

写法:

arr.reduce((previousValue, currentValue, currentIndex, array) => {
    // do something
 }, initialValue)

参数:
callbackfn
reduce 对于数组中第一个元素之后的每一个元素,按升序各调用一次回调函数。

initialValue(可选) :
作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;若没有指定初始值initialValue。 则previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。

callbackfn 回调有四个参数:
1. previousValue(前一次调用 callbackfn 得到的返回值)
2. currentValue(数组中正在处理的元素)
3. currentIndex(数组中正在处理的元素的索引)
4. array (被遍历的对象)

例子

// 求 0 + 1 + 2 + 3 + 4 + 5 = ?
  let arr = [1, 2, 3, 4, 5]
  let result = arr.reduce((previousValue, currentValue) => {
    return previousValue + currentValue
    // 别忘了:这里return 后的结果是下一次previousValue 的值
  }, 0)
  console.log('result', result) // 15
// 将二维数组转化为一维
  let arr = [[0, 1], [2, 3], [4, 5]]
  let result = arr.reduce((previousValue, currentValue) => {
    return previousValue.concat(currentValue)
  }, [])
  console.log('result', result) // [0, 1, 2, 3, 4, 5]
// 数字扁平化 又叫 数组拍平化
  const flatFn = arr => {
    return arr.reduce((previousValue, currentValue) => {
      return previousValue.concat(Array.isArray(currentValue) ? flatFn(currentValue) : currentValue)
    }, [])
  }
  const result = flatFn([1, 2, [3, 4, [5, 6]], [7, 8]])

  console.log('result', result)  // [1, 2, 3, 4, 5, 6, 7, 8]
// 数组去重
  let arr = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
  let result = arr.reduce((previousValue, currentValue) => {
    if(previousValue.indexOf(currentValue) === -1) {
      previousValue.push(currentValue)
    }
    return previousValue
  }, [])
  console.log('result', result) // ['a', 'b', 'c', 'e', 'd']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值