[譯] 圖解 Map、Reduce 和 Filter 陣列方法

mogic發表於2019-04-11

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]
複製程式碼

如果在這個陣列上使用 map 方法,比如在上面這個例子,會返回一個帶有 val > 10 判斷的和原始陣列長度相同的陣列,其中每個值都經過轉換或者檢查。如果原始值大於 10,會被轉換為真值。就像這樣:

[1, 4, 6, 14, 32, 78].map(val => val > 10)
// the result is: [false, false, false, true, true, true]
複製程式碼

但是 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"
複製程式碼

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

和我一起唱起來!

我想要用一首歌來結束這篇博文,給陣列方法寫了一個小調,來幫助你們記憶:

Video

如果發現譯文存在錯誤或其他需要改進的地方,歡迎到 掘金翻譯計劃 對譯文進行修改並 PR,也可獲得相應獎勵積分。文章開頭的 本文永久連結 即為本文在 GitHub 上的 MarkDown 連結。


掘金翻譯計劃 是一個翻譯優質網際網路技術文章的社群,文章來源為 掘金 上的英文分享文章。內容覆蓋 AndroidiOS前端後端區塊鏈產品設計人工智慧等領域,想要檢視更多優質譯文請持續關注 掘金翻譯計劃官方微博知乎專欄

相關文章