如何利用es6去重

如下是三種方法從數組裏去重,而且返回惟一的值。我最喜歡的方式是使用Set,由於它是最短最簡單的。es6

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轉爲數組code

另外呢,你也能夠使用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和filterrem

indexOf()get

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]

轉載自:http://www.lht.ren/article/12/

歡迎關注本人微信公衆號:乾貨技術

翻譯自:

https://medium.com/dailyjs/ho...

相關文章
相關標籤/搜索