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提供的新的数据结构。它类似于数组,但是成员的值是唯一的,没有重复的值。从而过滤掉了重复的值。
new Set(arr) //{1, "1", 2, 3, 4}
由于Set返回的并不是数组, 因此用扩展运算符(...)将Set返回的每一项数据取出,再用[]接收取出的数据就得到了一个无重复的数组。

浙公网安备 33010602011771号