JavaScript Array.prototype.reduce

前言

之前只知道 reduce 能够拿来作数组求和数组

但其实 reduce 的功能远不于此 因此在此作个总结markdown

用法

array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue);app

  • accumulator: 累加器 即函数上一次调用的返回值。ide

    第一次的时候为 initialValue || arr[0]函数

  • currentValue: 数组中函数正在处理的的值。ui

    第一次的时候 initialValue || arr[1]lua

  • currentIndex: (可选)数据中正在处理的元素索引url

    若是提供了 initialValue 从 0 开始 不然从 1 开始spa

  • array: (可选)调用 reduce 的数组3d

  • initialValue: (可选)累加器的初始值。没有时 累加器第一次的值为 currentValue

    注意: 在对没有设置初始值的空数组调用 reduce 方法时会报错。

为了更直观的感觉 咱们来看一个例子

//有初始值
;[1, 2, 3, 4].reduce(function (accumulator, currentValue, currentIndex, array) {
  return accumulator + currentValue
}, 10) // 20
复制代码
callback accumulator currentValue currentIndex array return value
first call 10(初始值) 1(数组第一个元素) 0(有初始值为 0) [1, 2, 3, 4] 11
second call 11 2 1 [1, 2, 3, 4] 13
third call 13 3 2 [1, 2, 3, 4] 16
fourth call 16 4 3 [1, 2, 3, 4] 20

使用场景

case1

能够作一个简单的数组求和

[1, 2, 3, 4].reduce((a, b) => a + b) // 10
复制代码

case2

能够将二维数组扁平化

[
  [1, 2],
  [3, 4],
  [5, 6],
].reduce((a, b) => a.concat(b), []) // [1, 2, 3, 4, 5, 6]
复制代码

case3

能够计算数组中每一个元素出现的次数

思路: 初始值设置为{} 用做咱们放结果的容器 而后若是容器中有这个元素 就value+1 没有就初始化key

[1, 2, 3, 1, 2, 3, 4].reduce((items, item) => {
  if (item in items) {
    items[item]++
  } else {
    items[item] = 1
  }
  return items
}, {}) // {1: 2, 2: 2, 3: 2, 4: 1}
复制代码

case4

数组去重

// 方法一
[
  1, 2, 3, 1, 2, 3, 4, 4, 5
].reduce((init, current) => {
  // 第一次的时候 init为空 将第一个元素push进init 
  // 而后之后每次的current都在init中找是否已经存在相同的元素
  // 没找到就继续push
  if (init.length === 0 || init.indexOf(current) === -1) {
    init.push(current)
  }
  return init
}, []) //[1, 2, 3, 4, 5]
复制代码
// 方法二
[1, 2, 3, 1, 2, 3, 4, 4, 5].sort().reduce((init, current) => {
  // 先将数组进行排序
  // 将第一个元素push 进 init
  // 判断之后的每个元素是否和init中最后一个元素相同
  // 如同不一样就继续push
  if (init.length === 0 || init[init.length - 1] !== current) {
    init.push(current)
  }
  return init
}, []) //[1, 2, 3, 4, 5]
复制代码
相关文章
相关标签/搜索