ES5数组的reduce方法

一、reduce方法接收2个参数

  参数1:function(accumulator, currentValue, index, arr) {},必须

    accumulator:必须,初始值(initialValue)或计算后的返回值(上次调用函数的返回值)

    currentValue:必须,当前元素

    index:可选,当前元素的索引

    arr:可选,当前元素所属的数组

  参数2:initialValue,可选,传递给函数的初始值

 

二、使用场景

  1、数组求和

    const arr = [1, 2, 3]
    const total = arr.reduce((acc, cur) => acc + cur)
    const total1 = arr.reduce((acc, cur) => acc + cur, 10)
    console.log(total) // 6
    console.log(total1) // 16

    一般来说,传了初始值会更安全

    const arr = []
    const total = arr.reduce((acc, cur) => acc + cur, 0) // 不传初始值会报错:Reduce of empty array with no initial value
    console.log(total) // 0

    数组对象中的属性求和

    const arr = [{ x: 1 }, { x: 2 }, { x: 3 }]
    const total = arr.reduce((acc, cur) => acc + cur.x, 0)
    console.log(total) // 6

    initialValue为0,必传。这里可以先通过map拿到所有的x,再求和,但是这样就多循环了几次

  2、二维数组转一维数组

    const arr = [[1, 2], [3, 4], [5, 6]]
    const newArr = arr.reduce((acc, cur) => acc.concat(cur), [])
    console.log(newArr) // [1, 2, 3, 4, 5, 6]

    多维数组转扁平化

    const arr = [
      [1, 2],
      [3, 4],
      [5, [6, 7, [8]]]
    ]
    const flatten = arr => arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur),[])
    const newArr = flatten(arr)
    console.log(newArr) // [1, 2, 3, 4, 5, 6, 7, 8]

  3、计算数组中每个元素出现的次数

    const arr = ['one', 'two', 'three', 'two', 'three', 'three']
    const count = arr.reduce((acc, cur) => {
      if (cur in acc) {
        acc[cur]++
      } else {
        acc[cur] = 1
      }
      return acc
    }, {})
    console.log(count) // {one: 1, two: 2, three: 3}

  4、去重

    const arr = [1, 2, 3, 4, 3, 2, 1]
    const newArr = arr.reduce((acc, cur) => {
      !acc.includes(cur) && acc.push(cur)
      return acc
    }, [])
    console.log(newArr) // [1, 2, 3, 4]

  5、按属性对object进行分类

    const people = [
      { name: 'Alice', age: 21 },
      { name: 'Max', age: 20 },
      { name: 'Jane', age: 20 }
    ]
    function groupBy(arr, property) {
      return arr.reduce((acc, cur) => {
        const key = cur[property]
        !acc[key] && (acc[key] = [])
        acc[key].push(cur)
        return acc
      }, {})
    }
    const res = groupBy(people, 'age')
    console.log(res) // {20: Array(2), 21: Array(1)}

 

posted @ 2022-04-07 16:47  吴小明-  阅读(148)  评论(0编辑  收藏  举报