集合是什么?一种无序且唯一的数据结构。ES6中有集合,名为Set。集合的常用操作:去重、判断某元素是否在集合中、求交集
let arr=[1,2,2,4,5,6,7,8,9,10]
let unRepeat=[...new Set(arr)]
console.log(unRepeat)let set1=new Set([1,2,3])
let set2=new Set([3,4,5])console.log(set1)//Intersection LeetCode:349.两个数组的交集
let intersection=new Set([...set1].filter(item=>set2.has(item)))
console.log(`intersection:`,union)
var intersection = function(nums1, nums2) {let set2=new Set(nums2);let set1=new Set(nums1)return [...set1].filter(item=>set2.has(item))
};//union 并集
let arrset1=[...set1]
let arrset2=[...set2]
let left=arrset1.filter(item=>!arrset2.includes(item))
let right=arrset2.filter(item=>!arrset1.includes(item))
let union=new Set([...left,...right])
console.log(`union:`,intersection)//差集
console.log('差集:',left,'or',right)//补集∁UA
let diffsection=new Set([...set2].filter(item=>!set1.has(item)))
console.log(`set1补集:`,diffsection)https://baijiahao.baidu.com/s?id=1757528805358274728&wfr=spider&for=pc
假设全集U={1,2,3,4,5,6},集合A={1,3,5},那么集合A在全集U中的补集就是由全集U中所有不属于A的元素组成的集合,即∁UA={2,4,6}。
使用Set对象:new、add、delete、has、size
weakset
迭代Set:多种迭代方法、Set与Array互转、求交集/差集
for of Array.from [....set1]