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]
複製代碼
相關文章
相關標籤/搜索