如何利用es6去重

以下是三種方法從數組裏去重,並且返回唯一的值。我最喜歡的方式是使用Set,因爲它是最短最簡單的。

const array = [5, 2, 4, 5, 3];
console.log([...new Set(array)])
console.log(array.filter((item, index) => array.indexOf(item) === index))
console.log(array.reduce((unique, item) => unique.includes(item) ? unique: [...unique, item], []))
// result: [5, 2, 4, 3]

使用Set

讓我開始解釋Set是什麼吧:

Set是由es6引入的一種新的數據對象,由於Set只允許你存儲唯一值,所以當傳遞進去一個數組的時候,它將會移除任何重複的值。

好啦,然我們回到我們的代碼中來看下到底都發生了什麼。實際上他進行了以下的操作:

  1. 首先,我們創建了新的Set並且把數組當作入參傳遞了進去,由於Set僅僅允許唯一值,所以所有重複值將會被移除。
  2. 現在重複值已經消失了,我們將會利用...把它重新轉爲數組。

const array = [5, 2, 4, 5, 3];
const set = new Set(array)
const newArr = [...set]
console.log(newArr)
// result: [5, 2, 4, 3]

使用Array.from()函數來吧Set轉爲數組

另外呢,你也可以使用Array.from()來吧Set轉爲數組。

const array = [5, 2, 4, 5, 3];
const set = new Set(array)
const newArr = Array.from(set)
console.log(newArr)
// result: [5, 2, 4, 3]

使用filter

爲了理解這個選項,讓我們來看看這兩個方法都做了什麼:indexOf和filter

indexOf()

indexOf()返回我們從數組裏找到的第一個元素的索引。

const array = [5, 2, 4, 5, 3];
console.log(array.indexOf(5)) // 0
console.log(array.indexOf(2)) // 1
console.log(array.indexOf(8)) // -1

filter

filter()函數會根據我們提供的條件創建一個新的數組。換一種說法,如果元素通過並且返回true,它將會包含在過濾後的數組中,如果有元素失敗並且返回false,那麼他就不會包含在過濾後的數組中。

我們逐步看看在每次循環數組的時候都發生了什麼。

const array = [5, 2, 4, 5, 3];
array.filter((item, index) => {
console.log(item, index, array.indexOf(item), array.indexOf(item) === index)
return array.indexOf(item) === index
})
//輸出
// 5 0 0 true
// 2 1 1 true
// 4 2 2 true
// 5 3 0 false
// 3 4 4 true
上面輸出的代碼見註釋。重複的元素不再於indexOf相匹配,所以在這些情況下,它的結果將會是false並且將不會被包含進過濾後的值當中。

檢索重複的值

我們也可以在數組中利用filter()函數來檢索重複的值。我們只需要像這樣簡單的調整下代碼:

const array = [5, 2, 4, 5, 3];
array.filter((item, index) => {
console.log(item, index, array.indexOf(item), array.indexOf(item) !== index)
return array.indexOf(item) !== index
})
//輸出
// 5 0 0 false
// 2 1 1 false
// 4 2 2 false
// 5 3 0 true
// 3 4 4 false

使用reduce()函數

reduce()函數用於減少數組的元素並根據你傳遞過去的reducer函數,把他們最終合併到一個最終的數組中,

在這種情況下,我們的reducer()函數我們最終的數組是否包含了這個元素,如果不包含,就吧他放進最終的數組中,反之則跳過這個元素,最後再返回我們最終的元素。

reduce()函數理解起來總是有那麼一點費勁,所以呢,咱們現在看下他是怎麼運行的。

const array = [5, 2, 4, 5, 3];
array.reduce((unique, item) => {
console.log(item, unique, unique.includes(item), unique.includes(item) ? unique: [...unique, item])
return unique.includes(item) ? unique: [...unique, item]
}, [])
//輸出
// 5 [] false [5]
// 2 [5] false [5, 2]
// 4 [5, 2] false [5, 2, 4]
// 5 [5, 2, 4] true [5, 2, 4]
// 3 [5, 2, 4] false [5, 2, 4, 3]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章