三種非破壞性處理數組的方法
在這篇文章中,我們將會探索處理數組的三種方法:
- for…of循環
- 數組方法.reduce()
- 數組方法.flatMap()
目的是幫助你在需要處理數組的時候在這些特性之間做出選擇。如果你還不知道.reduce()和.flatMap(),這里將向你解釋它們。
為了更好地感受這三個特性是如何工作的,我們分別使用它們來實現以下功能:
- 過濾一個輸入數組以產生一個輸出數組
- 將每個輸入數組元素映射為一個輸出數組元素
- 將每個輸入數組元素擴展為零個或多個輸出數組元素
- 過濾-映射(過濾和映射在一個步驟中)
- 計算一個數組的摘要
- 查找一個數組元素
- 檢查所有數組元素的條件
我們所做的一切都是「非破壞性的」:輸入的數組永遠不會被改變。如果輸出是一個數組,它永遠是新建的。
for-of循環
下面是數組如何通過for-of進行非破壞性的轉換:
- 首先聲明變量result,并用一個空數組初始化它。
- 對于輸入數組的每個元素elem:
- 對elem進行必要的轉換并將其推入result。
- 如果一個值應該被添加到result中:
使用for-of過濾
讓我們來感受一下通過for-of處理數組,并實現(簡易版的)數組方法.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來實現數組方法.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擴展
collectFruits()返回數組中所有人的所有水果:
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過濾&映射
下列代碼在一步中進行過濾以及映射:
/**
* 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計算摘要
getAverageGrade()計算了學生數組的平均等級:
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
);
注意事項:用小數點后的分數計算可能會導致四舍五入的錯誤。
使用for-of查找
for-of也擅長在未排序的數組中查找元素:
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來提前離開循環(A行)。
使用for-of檢查條件
當實現數組方法.every()時,我們再次從提前終止循環中獲益(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
);
何時使用
在處理數組時,for-of是一個非常常用的工具:
- 通過推送創建輸出數組很容易理解。
- 當結果不是數組時,我們可以通過return或break來提前結束循環,這通常很有用。
for-of的其他好處包括:
- 它可以與同步迭代一起工作。而且我們可以通過切換到for-await-of循環來支持異步迭代。
- 我們可以在允許使用await和yield操作的函數中使用它們。
for-of的缺點是,它可能比其他方法更冗長。這取決于我們試圖解決什么問題。
生成器和for-of
上一節已經提到了yield,但我還想指出,生成器對于處理和生產同步和異步迭代來說是多么的方便。
舉例來說,下面通過同步生成器來實現.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']
);
數組方法.reduce()
數組方法.reduce()讓我們計算數組的摘要。它是基于以下算法的:
- [初始化摘要] 我們用一個適用于空數組的值初始化摘要。
- 我們在數組上循環。每個數組元素:
- [更新摘要] 我們通過將舊的摘要與當前元素結合起來計算一個新的摘要。
在我們了解.reduce()之前,讓我們通過for-of來實現它的算法。我們將用串聯一個字符串數組作為一個例子:
function concatElements(arr) {
let summary = ''; // initializing
for (const element of arr) {
summary = summary + element; // updating
}
return summary;
}
assert.equal(
concatElements(['a', 'b', 'c']),
'abc'
);
數組方法.reduce()循環數組,并持續為我們跟蹤數組的摘要,因此可以聚焦于初始化和更新值。它使用"累加器"這一名稱作為"摘要"的粗略同義詞。.reduce()有兩個參數:
- 回調:
- 輸入:舊的累加器和當前元素
- 輸出:新的累加器
- 累加器的初始值。
在下面代碼中,我們使用.reduce()來實現concatElements():
const concatElements = (arr) => arr.reduce(
(accumulator, element) => accumulator + element, // updating
'' // initializing
);
使用.reduce()過濾
.reduce()是相當通用的。讓我們用它來實現過濾:
const filterArray = (arr, callback) => arr.reduce(
(acc, elem) => callback(elem) ? [...acc, elem] : acc,
[]
);
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
不過,當涉及到以非破壞性的方式向數組添加元素時,JavaScript 數組的效率并不高(與許多函數式編程語言中的鏈接列表相比)。因此,突變累加器的效率更高:
const filterArray = (arr, callback) => arr.reduce(
(acc, elem) => {
if (callback(elem)) {
acc.push(elem);
}
return acc;
},
[]
);
使用.reduce()映射
我們可以通過.reduce()來實現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()擴展
使用.reduce()進行擴展:
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()在一步中進行過濾和映射:
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()計算摘要
如果我們能在不改變累加器的情況下有效地計算出一個摘要,那么.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()實現的簡易版的數組方法.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()有一個限制:一旦我們找到一個值,我們仍然要訪問其余的元素,因為我們不能提前退出。不過for-of沒有這個限制。
使用.reduce()檢查條件
下面是使用.reduce()實現的簡易版的數組方法.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()中退出,這個實現會更有效率。
何時使用
.reduce()的一個優點是簡潔。缺點是它可能難以理解--特別是如果你不習慣于函數式編程的話。
以下情況我會使用.reduce():
- 我不需要對累加器進行變異。
- 我不需要提前退出。
- 我不需要對同步或異步迭代器的支持。
- 然而,為迭代器實現reduce是相對容易的。
只要能在不突變的情況下計算出一個摘要(比如所有元素的總和),.reduce()就是一個好工具。
不過,JavaScript并不擅長以非破壞性的方式增量創建數組。這就是為什么我在JavaScript中較少使用.reduce(),而在那些有內置不可變列表的語言中則較少使用相應的操作。
數組方法.flatMap()
普通的.map()方法將每個輸入元素精確地翻譯成一個輸出元素。
相比之下,.flatMap()可以將每個輸入元素翻譯成零個或多個輸出元素。為了達到這個目的,回調并不返回值,而是返回值的數組。它等價于在調用 map()方法后再調用深度為 1 的 flat() 方法(arr.map(...args).flat()),但比分別調用這兩個方法稍微更高效一些。
assert.equal(
[0, 1, 2, 3].flatMap(num => new Array(num).fill(String(num))),
['1', '2', '2', '3', '3', '3']
);
使用.flatMap()過濾
下面展示如何使用.flatMap()進行過濾:
const filterArray = (arr, callback) => arr.flatMap(
elem => callback(elem) ? [elem] : []
);
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
使用.flatMap()映射
下面展示如何使用.flatMap()進行映射:
const mapArray = (arr, callback) => arr.flatMap(
elem => [callback(elem)]
);
assert.deepEqual(
mapArray(['a', 'b', 'c'], str => str + str),
['aa', 'bb', 'cc']
);
使用.flatMap()過濾&映射
一步到位的過濾和映射是.flatMap()的優勢之一:
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()擴展
將輸入元素擴展為零或更多的輸出元素是.flatMap()的另一個優勢:
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()只能產生數組
使用.flatMap(),我們只能產生數組。這使得我們無法:
- 用.flatMap()計算摘要
- 用.flatMap()查找
- 用.flatMap()檢查條件
我們可以產生一個被數組包裹的值。然而,我們不能在回調的調用之間傳遞數據。而且我們不能提前退出。
何時使用
.flatMap()擅長:
- 同時進行過濾和映射
- 將輸入元素擴展為零或多個輸出元素
我還發現它相對容易理解。然而,它不像for-of和.reduce()那樣用途廣泛:
- 它只能產生數組作為結果。
- 我們不能在回調的調用之間傳遞數據。
- 我們不能提前退出。
建議
那么,我們如何最佳地使用這些工具來處理數組呢?我大致的建議是:
- 使用你所擁有的最具體的工具來完成這個任務:
你需要過濾嗎?請使用.filter()。
你需要映射嗎?請使用.map()。
你需要檢查元素的條件嗎?使用.some()或.every()。
等等。
- for-of是最通用的工具。根據我的經驗:
- 熟悉函數式編程的人,傾向于使用.reduce()和.flatMap()。
- 不熟悉函數式編程的人通常認為for-of更容易理解。然而,for-of通常會導致更多冗長的代碼。
- 如果不需要改變累加器,.reduce()擅長計算摘要(如所有元素的總和)。
- .flatMap()擅長于過濾&映射和將輸入元素擴展為零或更多的輸出元素。
本文譯自:https://2ality.com/2022/05/processing-arrays-non-destructively.html[1]
以上就是本文的全部內容,感謝閱讀。
參考資料
[1]https://2ality.com/2022/05/processing-arrays-non-destructively.html:https://2ality.com/2022/05/processing-arrays-non-destructively.html