以下是三種方法從數組裡去重,并且傳回唯一的值。我最喜歡的方式是使用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隻允許你存儲唯一值,是以當傳遞進去一個數組的時候,它将會移除任何重複的值。
好啦,然我們回到我們的代碼中來看下到底都發生了什麼。實際上他進行了以下的操作:
- 首先,我們建立了新的Set并且把數組當作入參傳遞了進去,由于Set僅僅允許唯一值,是以所有重複值将會被移除。
- 現在重複值已經消失了,我們将會利用...把它重新轉為數組。
const set = new Set(array)
const newArr = [...set]
console.log(newArr)
使用Array.from()函數來吧Set轉為數組
另外呢,你也可以使用Array.from()來吧Set轉為數組。
const newArr = Array.from(set)
使用filter
為了了解這個選項,讓我們來看看這兩個方法都做了什麼:indexOf和filter
indexOf()
indexOf()傳回我們從數組裡找到的第一個元素的索引。
console.log(array.indexOf(5)) // 0
console.log(array.indexOf(2)) // 1
console.log(array.indexOf(8)) // -1
filter
filter()函數會根據我們提供的條件建立一個新的數組。換一種說法,如果元素通過并且傳回true,它将會包含在過濾後的數組中,如果有元素失敗并且傳回false,那麼他就不會包含在過濾後的數組中。
我們逐漸看看在每次循環數組的時候都發生了什麼。
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()函數來檢索重複的值。我們隻需要像這樣簡單的調整下代碼:
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()函數了解起來總是有那麼一點費勁,是以呢,咱們現在看下他是怎麼運作的。
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]