ES6中的reduce

let arr1 = [0, 1, 2, 3, 4].reduce(function (accumulator, currentValue, currentIndex, array) {
        // accumulator 累计器
        // currentValue 当前值
        // currentIndex 当前索引
        // array 数组
        return accumulator + currentValue
      })
      // 等价于
      let arr2 = [0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr)
      console.log(arr2)

      // 提供一个初始值作为reduce()方法的第二个参数
      let arr3 = [0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
        return accumulator + currentValue
      }, 10)
      console.log(arr3)

      // 要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数
      let initialValue = 0
      let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
        return accumulator + currentValue.x
      }, initialValue)
      console.log(sum) //  6

      // 将二维数组转化为一维
      let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
        function (a, b) {
          return a.concat(b)
        },
        []
      )
      console.log(flattened)// [0, 1, 2, 3, 4, 5]

      // 计算数组中每个元素出现的次数
      let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']
      let countedNames = names.reduce(function (allNames, name) {
        if (name in allNames) {
          allNames[name]++
        } else {
          allNames[name] = 1
        }
        return allNames
      }, {})
      console.log(countedNames)

      // 按属性对object分类
      let people = [
        {name: 'Alice', age: 21},
        {name: 'Max', age: 20},
        {name: 'Jane', age: 20}
      ]

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

      let groupedPeople = groupBy(people, 'age')
      console.log(groupedPeople)

      // 数组去重
      let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
      let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
        if (accumulator.indexOf(currentValue) === -1) {
          accumulator.push(currentValue)
        }
        return accumulator
      }, [])

      console.log(myOrderedArray)

猜你喜欢

转载自www.cnblogs.com/ronle/p/11742875.html
今日推荐