[ 翻譯 ] ES6中數組去重的三種方法
原文:How to Remove Array Duplicates in ES6
翻譯:Hytonight雲息
有三種方法可以過濾掉一個數組的重複元素並且返回去重後的新數組。我最喜歡使用Set
,因為它最精簡。
const array = [??, 1, 2, ??,??, 3];
?
// 1: "Set"
[...new Set(array)];
?
// 2: "Filter"
array.filter((item, index) => array.indexOf(item) === index);
?
// 3: "Reduce"
array.reduce((unique, item) =>
unique.includes(item) ? unique : [...unique, item], []);
?
?
// RESULT:
// [??, 1, 2, 3];
1. 使用 Set
set
是ES6中引入的新的數據類型。set
只允許存儲不重複的值,所以當你放入一個數組,它會自動去掉重複的值。
OK,我們回去將代碼分解開來看,其實就做了兩件事情:
- 首先,我們通過原數組
array
創建了一個新的set
,所有的重複值都被去除了。 - 然後,我們通過展開運算符
…
轉換回了數組
const array = [??, 1, 2, ??,??, 3];
?
// Step 1
const uniqueSet = new Set(array);
// Set { ??, 1, 2, 3 }
?
// Step 2
const backToArray = [...uniqueSet];
// [??, 1, 2, 3]
當然,你也可以使用Array.form
來將set
轉回數組
const array = [??, 1, 2, ??,??, 3];
?
Array.from(new Set(array));
?
// [??, 1, 2, 3]
2.使用 filter()
為了更好地說明這個方法,我們得先說說這兩個方法:indexOf()
和filter()
。
indexOf
從一個數組中返回給定元素第一次出現的索引
const array = [??, 1, 2, ??,??, 3];
?
array.indexOf(??); // 0
array.indexOf(1); // 1
array.indexOf(2); // 2
array.indexOf(3); // 5
filter
filter()
方法通過給定的條件(一個函數)來返回一個新的數組。換句話說,如果輪到的這個元素進入了條件函數後結果為true
,那麼它將被加入到過濾後的新數組中,反之則不會加入到結果數組中。
const array = [??, 1, 2, ??,??, 3]
?
array.filter((item, index) => {
?
console.log(
// a. Item
item,
// b. Index
index,
// c. indexOf
array.indexOf(item),
// d. Condition
array.indexOf(item) === index,
);
?
return array.indexOf(item) === index
});
下面就是執行上述代碼後console
的輸出。可以看到,重複的元素就是那些index
和indexOf
不同的元素。所以,重複元素返回的結果就是false
。
(譯者按:說的再簡單點,就是所有重複元素只取第一次出現的那個,後來出現的丟棄)