在es6中新增了Set数据结构,它与数组类似,不同的是Set中的值是唯一的。
new Set()创建实例时可以传入数组,初始化set。
应用一:数组去重
let arr = [1,2,3,1,2] let set = new Set(arr)
let resArr = [...set]
console.log(resArr)
或者使用数组的from()方法,将set转换为数组
let arr = [1,2,3,1,2] let set = new Set(arr) let resArr = Array.from(set) console.log(resArr)
应用二:两个数组求交集
let arr1 = [1,2,3,1,2]
let arr2 = [1,2,4,5,1,2,4]
let set1 = new Set(arr1)
let set2 = new Set(arr2)
let sameArr = [...set1].filter(item => set2.has(item))
console.log(sameArr)
通过使用Set实例对象的has()方法,判断set2中是否含有item,含有返回true,否则返回false
应用三,两个数组的差集,与交集类似
let arr1 = [1,2,3,1,2] let arr2 = [1,2,4,5,1,2,4] let set1 = new Set(arr1) let set2 = new Set(arr2) let diffArr = [...set1].filter(item => !set2.has(item)) console.log(diffArr)
原文:https://www.cnblogs.com/xuwennn/p/13663394.html