原文: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的輸出。可以看到,重複的元素就是那些indexindexOf不同的元素。所以,重複元素返回的結果就是false

(譯者按:說的再簡單點,就是所有重複元素只取第一次出現的那個,後來出現的丟棄)

那如何得到重複的元素呢?

也是使用filter(),只要將上面的條件反一反就可以啦,如下:

const array = [??, 1, 2, ??,??, 3];
?
array.filter((item, index) => array.indexOf(item) !== index);
?
// [??,??]

3. 使用 reduce()

reduce()方法通過提供的reducer 函數來reduce數組中的元素並且將他們合併為一個新的數組。

(譯者按:難翻,看MDN解釋——reduce() 方法對數組中的每個元素執行一個由您提供的reducer函數(升序執行),將其結果匯總為單個返回值)

在這個例子中,我們的reducer函數用來檢查最終結果是否已經包含這個item。如果不包含,那麼將它放入最終結果,如果已經包含,則丟棄(或者說跳過)這個item

reduce常常會難以理解,所以我們一步步來看。

const array = [??, 1, 2, ??,??, 3];
?
array.reduce((unique, item) => {
console.log(
// a. Item
item,
// b. Final Array (Accumulator)
unique,
// c. Condition (Remember it only get pushed if this returns `false`)
unique.includes(item),
// d. Reducer Function Result
unique.includes(item) ? unique : [...unique, item],
);

return unique.includes(item) ? unique : [...unique, item]
}, []); // ?? The initial value of our Accumulator is an empty array
?
// RESULT:
// [??, 1, 2, 3];

console輸出如下:

推薦閱讀:

相关文章