1. 程式人生 > 實用技巧 >filter()、Set+擴充套件運算子陣列去重

filter()、Set+擴充套件運算子陣列去重

filter()陣列去重

let arr = [1, '1', 2, 2, 3, 4, 4];
let arr1 = arr.filter(function(item, index, self){
  return self.indexOf(item) === index
})
console.log(arr1)  //[1, "1", 2, 3, 4]

indexOf總是返回第一次匹配到元素的索引,後續重複的元素的索引值與indexOf返回的值不相等,從而被過濾掉。

引數 說明
item 必填。當前元素的值
index 選填。當前元素的索引值
self 選填。陣列本身


Set+擴充套件運算子陣列去重

let arr = [1, '1', 2, 2, 3, 4, 4];
let newArr = [...new Set(arr)]
console.log(newArr)  //[1, "1", 2, 3, 4]

Set是ES6提供的新的資料結構。它類似於陣列,但是成員的值是唯一的,沒有重複的值。從而過濾掉了重複的值。由於Set返回的並不是陣列

new Set(arr) //{1, "1", 2, 3, 4}

因此用擴充套件運算子(...)將Set返回的每一項資料取出,再用[]接收取出的資料就得到了一個無重複的陣列。