圖解 Map、Reduce 和 Filter 數組方法

map、reduce 和 filter 是三個非常實用的 JavaScript 數組方法,賦予了開發者四兩撥千斤的能力。我們直接進入正題,看看如何使用(並記住)這些超級好用的方法!

Array.map()

Array.map() 根據傳遞的轉換函數,更新給定數組中的每個值,並返回一個相同長度的新數組。它接受一個回調函數作爲參數,用以執行轉換過程。

let newArray = oldArray.map((value, index, array)  =>  {
...
});

一個幫助記住 map 的方法:Morph Array Piece-by-Piece(逐個改變數組)

你可以使用 map 代替 for-each 循環,來遍歷並對每個值應用轉換函數。這個方法適用於當你想更新數組的同時保留原始值。它不會潛在地刪除任何值(filter 方法會),也不會計算出一個新的輸出(就像 reduce 那樣)。map 允許你逐個改變數組。一起來看一個例子:

[1,  4,  6,  14,  32,  78].map(val => val *  10)
// the result is: [10, 40, 60, 140, 320, 780]

上面的例子中,我們使用一個初始數組([1, 4, 6, 14, 32, 78]),映射每個值到它自己的十倍(val * 10)。結果是一個新數組,初始數組的每個值被這個等式轉換:[10, 40, 60, 140, 320, 780]。

Array.filter()

當我們想要過濾數組的值到另一個數組,新數組中的每個值都通過一個特定檢查,Array.filter() 這個快捷實用的方法就派上用場了。

類似搜索過濾器,filter 基於傳遞的參數來過濾出值。

舉個例子,假定有個數字數組,想要過濾出大於 10 的值,可以這樣寫:

[1,  4,  6,  14,  32,  78].filter(val => val >  10)
// the result is: [14, 32, 78]

但是 filter 方法,只返回真值。因此如果所有值都執行指定的檢查的話,結果的長度會小於等於原始數組。

把 filter 想象成一個漏斗。部分混合物會從中穿過進入結果,而另一部分則會被留下並拋棄。

假設寵物訓練學校有一個四隻狗的小班,學校裏的所有狗都會經過各種挑戰,然後參加一個分級期末考試。我們用一個對象數組來表示這些狗狗:

const students =  [
  {
    name:  "Boops",
    finalGrade:  80
  },
  {
    name:  "Kitten",
    finalGrade:  45
  },
  {
    name:  "Taco",
    finalGrade:  100
  },
  {
    name:  "Lucy",
    finalGrade:  60
  }
]

如果狗狗們的期末考試成績高於 70 分,它們會獲得一個精美的證書;反之,它們就要去重修。爲了知道證書打印的數量,要寫一個方法來返回通過考試的狗狗。不必寫循環來遍歷數組的每個對象,我們可以用 filter 簡化代碼!

const passingDogs = students.filter((student)  =>  {
  return student.finalGrade >=  70
})
/*
passingDogs = [
  {
    name: "Boops",
    finalGrade: 80
  },
  {
    name: "Taco",
    finalGrade: 100
  }
]
*/

你也看到了,Boops 和 Taco 是好狗狗(其實所有狗都很不錯),它們取得了通過課程的成就證書!利用箭頭函數的隱式返回特性,一行代碼就能實現。因爲只有一個參數,所以可以刪掉箭頭函數的括號:

const passingDogs = students.filter(student => student.finalGrade >=  70)
/*
passingDogs = [
  {
    name: "Boops",
    finalGrade: 80
  },
  {
    name: "Taco",
    finalGrade: 100
  }
]
*/

Array.reduce()

reduce() 方法接受一個數組作爲輸入值並返回一個值。這點挺有趣的。reduce 接受一個回調函數,回調函數參數包括一個累計器(數組每一段的累加值,它會像雪球一樣增長),當前值,和索引。reduce 也接受一個初始值作爲第二個參數:

let finalVal = oldArray.reduce((accumulator, currentValue, currentIndex, array)  =>  {
...
}, initalValue);

來寫一個炒菜函數和一個作料清單:

// our list of ingredients in an array
const ingredients =  ['wine',  'tomato',  'onion',  'mushroom']
// a cooking function
const cook =  (ingredient)  =>  {
  return  `cooked ${ingredient}`
}

如果我們想要把這些作料做成一個調味汁(開玩笑的),用 reduce() 來歸約!

const wineReduction = ingredients.reduce((sauce, item)  =>  {
  return sauce += cook(item)  +  ', '
},  '')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "

初始值(這個例子中的 '')很重要,它決定了第一個作料能夠進行烹飪。這裏輸出的結果不太靠譜,自己炒菜時要當心。下面的例子就是我要說到的情況:

const wineReduction = ingredients.reduce((sauce, item)  =>  {
  return sauce += cook(item)  +  ', '
})
// wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "

最後,確保新字符串的末尾沒有額外的空白,我們可以傳遞索引和數組來執行轉換:

const wineReduction = ingredients.reduce((sauce, item, index, array)  =>  {
  sauce += cook(item)
  if  (index < array.length -  1)  {
    sauce +=  ', '
  }
  return sauce
},  '')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

可以用三目操作符、模板字符串和隱式返回,寫的更簡潔(一行搞定!):

const wineReduction = ingredients.reduce((sauce, item, index, array)  =>  {
return  (index < array.length -  1)  ? sauce +=  `${cook(item)},`  : sauce +=  `${cook(item)}`
},  '')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

記住這個方法的簡單辦法就是回想你怎麼做調味汁:把多個作料歸約到單個。

喜歡你就點個贊。看完文章,還有福利拿,往下看👇👇👇
感興趣的小夥伴可以在公號【grain先森】後臺回覆【190414】獲取7張html、css思維導圖,也可以轉發朋友圈和你的朋友分享哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章