三種非破壞性處理數(shù)組的方法
在這篇文章中,我們將會(huì)探索處理數(shù)組的三種方法:
- for…of循環(huán)
- 數(shù)組方法.reduce()
- 數(shù)組方法.flatMap()
目的是幫助你在需要處理數(shù)組的時(shí)候在這些特性之間做出選擇。如果你還不知道.reduce()和.flatMap(),這里將向你解釋它們。
為了更好地感受這三個(gè)特性是如何工作的,我們分別使用它們來實(shí)現(xiàn)以下功能:
- 過濾一個(gè)輸入數(shù)組以產(chǎn)生一個(gè)輸出數(shù)組
- 將每個(gè)輸入數(shù)組元素映射為一個(gè)輸出數(shù)組元素
- 將每個(gè)輸入數(shù)組元素?cái)U(kuò)展為零個(gè)或多個(gè)輸出數(shù)組元素
- 過濾-映射(過濾和映射在一個(gè)步驟中)
- 計(jì)算一個(gè)數(shù)組的摘要
- 查找一個(gè)數(shù)組元素
- 檢查所有數(shù)組元素的條件
我們所做的一切都是「非破壞性的」:輸入的數(shù)組永遠(yuǎn)不會(huì)被改變。如果輸出是一個(gè)數(shù)組,它永遠(yuǎn)是新建的。
for-of循環(huán)
下面是數(shù)組如何通過for-of進(jìn)行非破壞性的轉(zhuǎn)換:
- 首先聲明變量result,并用一個(gè)空數(shù)組初始化它。
- 對(duì)于輸入數(shù)組的每個(gè)元素elem:
- 對(duì)elem進(jìn)行必要的轉(zhuǎn)換并將其推入result。
- 如果一個(gè)值應(yīng)該被添加到result中:
使用for-of過濾
讓我們來感受一下通過for-of處理數(shù)組,并實(shí)現(xiàn)(簡(jiǎn)易版的)數(shù)組方法.filter():
function filterArray(arr, callback) {
const result = [];
for (const elem of arr) {
if (callback(elem)) {
result.push(elem);
}
}
return result;
}
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
使用for-of映射
我們也可以使用for-of來實(shí)現(xiàn)數(shù)組方法.map()。
function mapArray(arr, callback) {
const result = [];
for (const elem of arr) {
result.push(callback(elem));
}
return result;
}
assert.deepEqual(
mapArray(['a', 'b', 'c'], str => str + str),
['aa', 'bb', 'cc']
);
使用for-of擴(kuò)展
collectFruits()返回?cái)?shù)組中所有人的所有水果:
function collectFruits(persons) {
const result = [];
for (const person of persons) {
result.push(...person.fruits);
}
return result;
}
const PERSONS = [
{
name: 'Jane',
fruits: ['strawberry', 'raspberry'],
},
{
name: 'John',
fruits: ['apple', 'banana', 'orange'],
},
{
name: 'Rex',
fruits: ['melon'],
},
];
assert.deepEqual(
collectFruits(PERSONS),
['strawberry', 'raspberry', 'apple', 'banana', 'orange', 'melon']
);
使用for-of過濾&映射
下列代碼在一步中進(jìn)行過濾以及映射:
/**
* What are the titles of movies whose rating is at least `minRating`?
*/
function getTitles(movies, minRating) {
const result = [];
for (const movie of movies) {
if (movie.rating >= minRating) { // (A)
result.push(movie.title); // (B)
}
}
return result;
}
const MOVIES = [
{ title: 'Inception', rating: 8.8 },
{ title: 'Arrival', rating: 7.9 },
{ title: 'Groundhog Day', rating: 8.1 },
{ title: 'Back to the Future', rating: 8.5 },
{ title: 'Being John Malkovich', rating: 7.8 },
];
assert.deepEqual(
getTitles(MOVIES, 8),
['Inception', 'Groundhog Day', 'Back to the Future']
);
- 過濾是通過A行的if語句和B行的.push()方法完成的。
- 映射是通過推送movie.title(而不是元素movie)完成的。
使用for-of計(jì)算摘要
getAverageGrade()計(jì)算了學(xué)生數(shù)組的平均等級(jí):
function getAverageGrade(students) {
let sumOfGrades = 0;
for (const student of students) {
sumOfGrades += student.grade;
}
return sumOfGrades / students.length;
}
const STUDENTS = [
{
id: 'qk4k4yif4a',
grade: 4.0,
},
{
id: 'r6vczv0ds3',
grade: 0.25,
},
{
id: '9s53dn6pbk',
grade: 1,
},
];
assert.equal(
getAverageGrade(STUDENTS),
1.75
);
注意事項(xiàng):用小數(shù)點(diǎn)后的分?jǐn)?shù)計(jì)算可能會(huì)導(dǎo)致四舍五入的錯(cuò)誤。
使用for-of查找
for-of也擅長(zhǎng)在未排序的數(shù)組中查找元素:
function findInArray(arr, callback) {
for (const [index, value] of arr.entries()) {
if (callback(value)) {
return {index, value}; // (A)
}
}
return undefined;
}
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 0),
{index: 1, value: 'a'}
);
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 1),
undefined
);
這里,一旦我們找到了什么,我們就可以通過return來提前離開循環(huán)(A行)。
使用for-of檢查條件
當(dāng)實(shí)現(xiàn)數(shù)組方法.every()時(shí),我們?cè)俅螐奶崆敖K止循環(huán)中獲益(A行):
function everyArrayElement(arr, condition) {
for (const elem of arr) {
if (!condition(elem)) {
return false; // (A)
}
}
return true;
}
assert.equal(
everyArrayElement(['a', '', 'b'], str => str.length > 0),
false
);
assert.equal(
everyArrayElement(['a', 'b'], str => str.length > 0),
true
);
何時(shí)使用
在處理數(shù)組時(shí),for-of是一個(gè)非常常用的工具:
- 通過推送創(chuàng)建輸出數(shù)組很容易理解。
- 當(dāng)結(jié)果不是數(shù)組時(shí),我們可以通過return或break來提前結(jié)束循環(huán),這通常很有用。
for-of的其他好處包括:
- 它可以與同步迭代一起工作。而且我們可以通過切換到for-await-of循環(huán)來支持異步迭代。
- 我們可以在允許使用await和yield操作的函數(shù)中使用它們。
for-of的缺點(diǎn)是,它可能比其他方法更冗長(zhǎng)。這取決于我們?cè)噲D解決什么問題。
生成器和for-of
上一節(jié)已經(jīng)提到了yield,但我還想指出,生成器對(duì)于處理和生產(chǎn)同步和異步迭代來說是多么的方便。
舉例來說,下面通過同步生成器來實(shí)現(xiàn).filter()和.map():
function* filterIterable(iterable, callback) {
for (const item of iterable) {
if (callback(item)) {
yield item;
}
}
}
const iterable1 = filterIterable(
['', 'a', '', 'b'],
str => str.length > 0
);
assert.deepEqual(
Array.from(iterable1),
['a', 'b']
);
function* mapIterable(iterable, callback) {
for (const item of iterable) {
yield callback(item);
}
}
const iterable2 = mapIterable(['a', 'b', 'c'], str => str + str);
assert.deepEqual(
Array.from(iterable2),
['aa', 'bb', 'cc']
);
數(shù)組方法.reduce()
數(shù)組方法.reduce()讓我們計(jì)算數(shù)組的摘要。它是基于以下算法的:
- [初始化摘要] 我們用一個(gè)適用于空數(shù)組的值初始化摘要。
- 我們?cè)跀?shù)組上循環(huán)。每個(gè)數(shù)組元素:
- [更新摘要] 我們通過將舊的摘要與當(dāng)前元素結(jié)合起來計(jì)算一個(gè)新的摘要。
在我們了解.reduce()之前,讓我們通過for-of來實(shí)現(xiàn)它的算法。我們將用串聯(lián)一個(gè)字符串?dāng)?shù)組作為一個(gè)例子:
function concatElements(arr) {
let summary = ''; // initializing
for (const element of arr) {
summary = summary + element; // updating
}
return summary;
}
assert.equal(
concatElements(['a', 'b', 'c']),
'abc'
);
數(shù)組方法.reduce()循環(huán)數(shù)組,并持續(xù)為我們跟蹤數(shù)組的摘要,因此可以聚焦于初始化和更新值。它使用"累加器"這一名稱作為"摘要"的粗略同義詞。.reduce()有兩個(gè)參數(shù):
- 回調(diào):
- 輸入:舊的累加器和當(dāng)前元素
- 輸出:新的累加器
- 累加器的初始值。
在下面代碼中,我們使用.reduce()來實(shí)現(xiàn)concatElements():
const concatElements = (arr) => arr.reduce(
(accumulator, element) => accumulator + element, // updating
'' // initializing
);
使用.reduce()過濾
.reduce()是相當(dāng)通用的。讓我們用它來實(shí)現(xiàn)過濾:
const filterArray = (arr, callback) => arr.reduce(
(acc, elem) => callback(elem) ? [...acc, elem] : acc,
[]
);
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
不過,當(dāng)涉及到以非破壞性的方式向數(shù)組添加元素時(shí),JavaScript 數(shù)組的效率并不高(與許多函數(shù)式編程語言中的鏈接列表相比)。因此,突變累加器的效率更高:
const filterArray = (arr, callback) => arr.reduce(
(acc, elem) => {
if (callback(elem)) {
acc.push(elem);
}
return acc;
},
[]
);
使用.reduce()映射
我們可以通過.reduce()來實(shí)現(xiàn)map:
const mapArray = (arr, callback) => arr.reduce(
(acc, elem) => [...acc, callback(elem)],
[]
);
assert.deepEqual(
mapArray(['a', 'b', 'c'], str => str + str),
['aa', 'bb', 'cc']
);
下面是效率更高的突變版本:
const mapArray = (arr, callback) => arr.reduce(
(acc, elem) => {
acc.push(callback(elem));
return acc;
},
[]
);
使用.reduce()擴(kuò)展
使用.reduce()進(jìn)行擴(kuò)展:
const collectFruits = (persons) => persons.reduce(
(acc, person) => [...acc, ...person.fruits],
[]
);
const PERSONS = [
{
name: 'Jane',
fruits: ['strawberry', 'raspberry'],
},
{
name: 'John',
fruits: ['apple', 'banana', 'orange'],
},
{
name: 'Rex',
fruits: ['melon'],
},
];
assert.deepEqual(
collectFruits(PERSONS),
['strawberry', 'raspberry', 'apple', 'banana', 'orange', 'melon']
);
突變版本:
const collectFruits = (persons) => persons.reduce(
(acc, person) => {
acc.push(...person.fruits);
return acc;
},
[]
);
使用.reduce()過濾&映射
使用.reduce()在一步中進(jìn)行過濾和映射:
const getTitles = (movies, minRating) => movies.reduce(
(acc, movie) => (movie.rating >= minRating)
? [...acc, movie.title]
: acc,
[]
);
const MOVIES = [
{ title: 'Inception', rating: 8.8 },
{ title: 'Arrival', rating: 7.9 },
{ title: 'Groundhog Day', rating: 8.1 },
{ title: 'Back to the Future', rating: 8.5 },
{ title: 'Being John Malkovich', rating: 7.8 },
];
assert.deepEqual(
getTitles(MOVIES, 8),
['Inception', 'Groundhog Day', 'Back to the Future']
);
效率更高的突變版本:
const getTitles = (movies, minRating) => movies.reduce(
(acc, movie) => {
if (movie.rating >= minRating) {
acc.push(movie.title);
}
return acc;
},
[]
);
使用.reduce()計(jì)算摘要
如果我們能在不改變累加器的情況下有效地計(jì)算出一個(gè)摘要,那么.reduce()就很出色:
const getAverageGrade = (students) => {
const sumOfGrades = students.reduce(
(acc, student) => acc + student.grade,
0
);
return sumOfGrades / students.length;
};
const STUDENTS = [
{
id: 'qk4k4yif4a',
grade: 4.0,
},
{
id: 'r6vczv0ds3',
grade: 0.25,
},
{
id: '9s53dn6pbk',
grade: 1,
},
];
assert.equal(
getAverageGrade(STUDENTS),
1.75
);
使用.reduce()查找
下面是使用.reduce()實(shí)現(xiàn)的簡(jiǎn)易版的數(shù)組方法.find():
const findInArray = (arr, callback) => arr.reduce(
(acc, value, index) => (acc === undefined && callback(value))
? {index, value}
: acc,
undefined
);
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 0),
{index: 1, value: 'a'}
);
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 1),
undefined
);
這里.reduce()有一個(gè)限制:一旦我們找到一個(gè)值,我們?nèi)匀灰L問其余的元素,因?yàn)槲覀儾荒芴崆巴顺?。不過for-of沒有這個(gè)限制。
使用.reduce()檢查條件
下面是使用.reduce()實(shí)現(xiàn)的簡(jiǎn)易版的數(shù)組方法.every():
const everyArrayElement = (arr, condition) => arr.reduce(
(acc, elem) => !acc ? acc : condition(elem),
true
);
assert.equal(
everyArrayElement(['a', '', 'b'], str => str.length > 0),
false
);
assert.equal(
everyArrayElement(['a', 'b'], str => str.length > 0),
true
);
同樣的,如果我們能提前從.reduce()中退出,這個(gè)實(shí)現(xiàn)會(huì)更有效率。
何時(shí)使用
.reduce()的一個(gè)優(yōu)點(diǎn)是簡(jiǎn)潔。缺點(diǎn)是它可能難以理解--特別是如果你不習(xí)慣于函數(shù)式編程的話。
以下情況我會(huì)使用.reduce():
- 我不需要對(duì)累加器進(jìn)行變異。
- 我不需要提前退出。
- 我不需要對(duì)同步或異步迭代器的支持。
- 然而,為迭代器實(shí)現(xiàn)reduce是相對(duì)容易的。
只要能在不突變的情況下計(jì)算出一個(gè)摘要(比如所有元素的總和),.reduce()就是一個(gè)好工具。
不過,JavaScript并不擅長(zhǎng)以非破壞性的方式增量創(chuàng)建數(shù)組。這就是為什么我在JavaScript中較少使用.reduce(),而在那些有內(nèi)置不可變列表的語言中則較少使用相應(yīng)的操作。
數(shù)組方法.flatMap()
普通的.map()方法將每個(gè)輸入元素精確地翻譯成一個(gè)輸出元素。
相比之下,.flatMap()可以將每個(gè)輸入元素翻譯成零個(gè)或多個(gè)輸出元素。為了達(dá)到這個(gè)目的,回調(diào)并不返回值,而是返回值的數(shù)組。它等價(jià)于在調(diào)用 map()方法后再調(diào)用深度為 1 的 flat() 方法(arr.map(...args).flat()),但比分別調(diào)用這兩個(gè)方法稍微更高效一些。
assert.equal(
[0, 1, 2, 3].flatMap(num => new Array(num).fill(String(num))),
['1', '2', '2', '3', '3', '3']
);
使用.flatMap()過濾
下面展示如何使用.flatMap()進(jìn)行過濾:
const filterArray = (arr, callback) => arr.flatMap(
elem => callback(elem) ? [elem] : []
);
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
使用.flatMap()映射
下面展示如何使用.flatMap()進(jìn)行映射:
const mapArray = (arr, callback) => arr.flatMap(
elem => [callback(elem)]
);
assert.deepEqual(
mapArray(['a', 'b', 'c'], str => str + str),
['aa', 'bb', 'cc']
);
使用.flatMap()過濾&映射
一步到位的過濾和映射是.flatMap()的優(yōu)勢(shì)之一:
const getTitles = (movies, minRating) => movies.flatMap(
(movie) => (movie.rating >= minRating) ? [movie.title] : []
);
const MOVIES = [
{ title: 'Inception', rating: 8.8 },
{ title: 'Arrival', rating: 7.9 },
{ title: 'Groundhog Day', rating: 8.1 },
{ title: 'Back to the Future', rating: 8.5 },
{ title: 'Being John Malkovich', rating: 7.8 },
];
assert.deepEqual(
getTitles(MOVIES, 8),
['Inception', 'Groundhog Day', 'Back to the Future']
);
使用.flatMap()擴(kuò)展
將輸入元素?cái)U(kuò)展為零或更多的輸出元素是.flatMap()的另一個(gè)優(yōu)勢(shì):
const collectFruits = (persons) => persons.flatMap(
person => person.fruits
);
const PERSONS = [
{
name: 'Jane',
fruits: ['strawberry', 'raspberry'],
},
{
name: 'John',
fruits: ['apple', 'banana', 'orange'],
},
{
name: 'Rex',
fruits: ['melon'],
},
];
assert.deepEqual(
collectFruits(PERSONS),
['strawberry', 'raspberry', 'apple', 'banana', 'orange', 'melon']
);
.flatMap()只能產(chǎn)生數(shù)組
使用.flatMap(),我們只能產(chǎn)生數(shù)組。這使得我們無法:
- 用.flatMap()計(jì)算摘要
- 用.flatMap()查找
- 用.flatMap()檢查條件
我們可以產(chǎn)生一個(gè)被數(shù)組包裹的值。然而,我們不能在回調(diào)的調(diào)用之間傳遞數(shù)據(jù)。而且我們不能提前退出。
何時(shí)使用
.flatMap()擅長(zhǎng):
- 同時(shí)進(jìn)行過濾和映射
- 將輸入元素?cái)U(kuò)展為零或多個(gè)輸出元素
我還發(fā)現(xiàn)它相對(duì)容易理解。然而,它不像for-of和.reduce()那樣用途廣泛:
- 它只能產(chǎn)生數(shù)組作為結(jié)果。
- 我們不能在回調(diào)的調(diào)用之間傳遞數(shù)據(jù)。
- 我們不能提前退出。
建議
那么,我們?nèi)绾巫罴训厥褂眠@些工具來處理數(shù)組呢?我大致的建議是:
- 使用你所擁有的最具體的工具來完成這個(gè)任務(wù):
你需要過濾嗎?請(qǐng)使用.filter()。
你需要映射嗎?請(qǐng)使用.map()。
你需要檢查元素的條件嗎?使用.some()或.every()。
等等。
- for-of是最通用的工具。根據(jù)我的經(jīng)驗(yàn):
- 熟悉函數(shù)式編程的人,傾向于使用.reduce()和.flatMap()。
- 不熟悉函數(shù)式編程的人通常認(rèn)為for-of更容易理解。然而,for-of通常會(huì)導(dǎo)致更多冗長(zhǎng)的代碼。
- 如果不需要改變累加器,.reduce()擅長(zhǎng)計(jì)算摘要(如所有元素的總和)。
- .flatMap()擅長(zhǎng)于過濾&映射和將輸入元素?cái)U(kuò)展為零或更多的輸出元素。
本文譯自:https://2ality.com/2022/05/processing-arrays-non-destructively.html[1]
以上就是本文的全部?jī)?nèi)容,感謝閱讀。
參考資料
[1]https://2ality.com/2022/05/processing-arrays-non-destructively.html:https://2ality.com/2022/05/processing-arrays-non-destructively.html