首頁  >  文章  >  web前端  >  如何使用es6實作去重(程式碼範例)

如何使用es6實作去重(程式碼範例)

不言
不言轉載
2019-01-16 09:56:092924瀏覽

這篇文章帶給大家的內容是關於如何使用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轉為數組

另外呢,你也可以使用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]
######

以上是如何使用es6實作去重(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除