Map、Reduce 和 Filter 数组方法

[Vue中文社区](javascript:void(0);) 5月21日

英文:Una Kravets 译文:熊贤仁

https://juejin.im/post/5caf030d6fb9a068736d2d7c

map、reduce 和 filter 是三个非常实用的 JavaScript 数组方法,赋予了开发者四两拨千斤的能力。我们直接进入正题,看看如何使用(并记住)这些超级好用的方法!

Array.map()

Array.map() 根据传递的转换函数,更新给定数组中的每个值,并返回一个相同长度的新数组。它接受一个回调函数作为参数,用以执行转换过程。

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

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

  2. ...

  3. });

</pre>

一个帮助记住 map 的方法:Morph Array Piece-by-Piece(逐个改变数组)

你可以使用 map 代替 for-each 循环,来遍历并对每个值应用转换函数。这个方法适用于当你想更新数组的同时保留原始值。它不会潜在地删除任何值(filter 方法会),也不会计算出一个新的输出(就像 reduce 那样)。map 允许你逐个改变数组。一起来看一个例子:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. [1, 4, 6, 14, 32, 78].map(val => val * 10)

  2. // the result is: [10, 40, 60, 140, 320, 780]

</pre>

上面的例子中,我们使用一个初始数组([1, 4, 6, 14, 32, 78]),映射每个值到它自己的十倍(val * 10)。结果是一个新数组,初始数组的每个值被这个等式转换:[10, 40, 60, 140, 320, 780]。

image

Array.filter()

当我们想要过滤数组的值到另一个数组,新数组中的每个值都通过一个特定检查,Array.filter() 这个快捷实用的方法就派上用场了。

类似搜索过滤器,filter 基于传递的参数来过滤出值。

举个例子,假定有个数字数组,想要过滤出大于 10 的值,可以这样写:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. [1, 4, 6, 14, 32, 78].filter(val => val > 10)

  2. // the result is: [14, 32, 78]

</pre>

但是 filter 方法,只返回真值。因此如果所有值都执行指定的检查的话,结果的长度会小于等于原始数组。

把 filter 想象成一个漏斗。部分混合物会从中穿过进入结果,而另一部分则会被留下并抛弃。

image

假设宠物训练学校有一个四只狗的小班,学校里的所有狗都会经过各种挑战,然后参加一个分级期末考试。我们用一个对象数组来表示这些狗狗:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. const students = [

  2. {

  3. name: "Boops",

  4. finalGrade: 80

  5. },

  6. {

  7. name: "Kitten",

  8. finalGrade: 45

  9. },

  10. {

  11. name: "Taco",

  12. finalGrade: 100

  13. },

  14. {

  15. name: "Lucy",

  16. finalGrade: 60

  17. }

  18. ]

</pre>

如果狗狗们的期末考试成绩高于 70 分,它们会获得一个精美的证书;反之,它们就要去重修。为了知道证书打印的数量,要写一个方法来返回通过考试的狗狗。不必写循环来遍历数组的每个对象,我们可以用 filter 简化代码!

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. const passingDogs = students.filter((student) => {

  2. return student.finalGrade >= 70

  3. })

  4. /*

  5. passingDogs = [

  6. {

  7. name: "Boops",

  8. finalGrade: 80

  9. },

  10. {

  11. name: "Taco",

  12. finalGrade: 100

  13. }

  14. ]

  15. */

</pre>

你也看到了,Boops 和 Taco 是好狗狗(其实所有狗都很不错),它们取得了通过课程的成就证书!利用箭头函数的隐式返回特性,一行代码就能实现。因为只有一个参数,所以可以删掉箭头函数的括号:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. const passingDogs = students.filter(student => student.finalGrade >= 70)

  2. /*

  3. passingDogs = [

  4. {

  5. name: "Boops",

  6. finalGrade: 80

  7. },

  8. {

  9. name: "Taco",

  10. finalGrade: 100

  11. }

  12. ]

  13. */

</pre>

Array.reduce()

reduce() 方法接受一个数组作为输入值并返回一个值。这点挺有趣的。reduce 接受一个回调函数,回调函数参数包括一个累计器(数组每一段的累加值,它会像雪球一样增长),当前值,和索引。reduce 也接受一个初始值作为第二个参数:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. let finalVal = oldArray.reduce((accumulator, currentValue, currentIndex, array) => {

  2. ...

  3. }), initalValue;

</pre>

image

来写一个炒菜函数和一个作料清单:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. // our list of ingredients in an array

  2. const ingredients = ['wine', 'tomato', 'onion', 'mushroom']

  3. // a cooking function

  4. const cook = (ingredient) => {

  5. returncooked ${ingredient}``

  6. }

</pre>

如果我们想要把这些作料做成一个调味汁(开玩笑的),用 reduce() 来归约!

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. const wineReduction = ingredients.reduce((sauce, item) => {

  2. return sauce += cook(item) + ', '

  3. }, '')

  4. // wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "

</pre>

初始值(这个例子中的 '')很重要,它决定了第一个作料能够进行烹饪。这里输出的结果不太靠谱,自己炒菜时要当心。下面的例子就是我要说到的情况:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. const wineReduction = ingredients.reduce((sauce, item) => {

  2. return sauce += cook(item) + ', '

  3. })

  4. // wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "

</pre>

最后,确保新字符串的末尾没有额外的空白,我们可以传递索引和数组来执行转换:

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. const wineReduction = ingredients.reduce((sauce, item, index, array) => {

  2. sauce += cook(item)

  3. if (index < array.length - 1) {

  4. sauce += ', '

  5. }

  6. return sauce

  7. }, '')

  8. // wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

</pre>

可以用三目操作符、模板字符串和隐式返回,写的更简洁(一行搞定!):

<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">

  1. const wineReduction = ingredients.reduce((sauce, item, index, array) => {

  2. return (index < array.length - 1) ? sauce +={cook(item)}, ` : sauce += `{cook(item)}``

  3. }, '')

  4. // wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

</pre>

记住这个方法的简单办法就是回想你怎么做调味汁:把多个作料归约到单个。

和我一起唱起来!

我想要用一首歌来结束这篇博文,给数组方法写了一个小调,来帮助你们记忆:

视频地址:https://youtu.be/-YEbBy3Mk

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容