JavaScrip中 Array.reduce()

数组的方法 reduce()

reduce方法在数组的每一项元素上都会执行回调函数。

语法array.reduce( callBack [ , init]  )

// 语法
arrary.reduce(function(pre, val, ind, arr){ // .... }, init)

回调函数的参数有:初始值/上一次回调返回值、当前元素、当前索引、原数组。

callBack 函数:callBack(pre, val, ind, arr)。

  pre:初始值init  或 上一次回调函数的返回值。提供初始值init,作为首次回调函数的第一个参数pre的值使用。

  val: 当前元素。

  ind: 当前索引。

  arr: 原数组。

init初始值:作为首次回调函数的第一个参数的pre值使用。

1.求和

const array = [1, 2, 3, 4, 5]
const total
= array.reduce((pre, val) => pre + val, 0)
console.log(total)
// 15
const array = [
    { num: 10 },
    { num: 20 },
    { num: 30 }
]
const total = array.reduce((pre, val) => pre + val.num, 0)
console.log(total) // 60

2.最大值

   const array = [1, 2, 3, 8, 5, 2, 4]
   const max = array.reduce((pre, val) => Math.max(pre, val))
// const max = array.reduce((pre, val) => pre > val ? pre : val)
// const max = arrary.reduce(pre, val) => Math.max(pre, val), array[0]) console.log(max )
// 8
   const array = [
       { num: 120 },
       { num: 10 },
       { num: 200 },
       { num: 30 }
   ]
   const max= array.reduce((pre, val) => Math.max(pre, val.num), array[0].num)
// const
max= array.reduce((pre, val) => Math.max(typeof pre === 'number' ? pre : pre.num, val.num))
console.log(max) // 200

3.其他用法

const array = [
      { age: 18, name: '花花' },
      { age: 19, name: '韩梅' },
      { age: 16, name: '小白' },
      { age: 17, name: '框猪' }
]
const res = array.reduce((pre, val, ind, arr) => {
      let s = ''
      let e = ''
      switch (ind) {
        case 0:
          s = ''
          break
        case arr.length - 1:
          s = '和'
          e = '。'
          break
        default:
          s = '、'
      }
      return pre + `${s}${val.name}${e}`
}, '参与者有')
console.log(res) // 参与者有花花、韩梅、小白和框猪。
const array = [
      { age: 18, name: '花花', type: 1 },
      { age: 19, name: '韩梅', type: 3 },
      { age: 16, name: '小白', type: 2 },
      { age: 17, name: '框猪', type: 1 },
      { age: 17, name: '懵萌', type: 1 },
      { age: 20, name: '大卫', type: 3 }
]
const Obj = array.reduce((pre, val) => {
      pre[val.type] ? pre[val.type].push(val) : pre[val.type] = [val]
      return pre
}, {})

console.log(Obj)

/*  实现数组分类
  {
    1:
[
        { age: 18, name: '花花', type: 1 },
        { age: 17, name: '框猪', type: 1 },
        { age: 17, name: '懵萌', type: 1 }
    ],
    2: [
      { age: 16, name: '小白', type: 2 }
    ],
    3: [
      { age: 19, name: '韩梅', type: 3 },
      { age: 20, name: '大卫', type: 3 }
    ]
  }
*/ 
原文地址:https://www.cnblogs.com/zhaoxiaoying/p/14658535.html