var arr1=[1,2,3,4],arr2=[2,3,8],arr3=[3,4,5,6];
var set1=new Set(arr1),set2=new Set(arr2),set3=new Set(arr3);
//交集:arr1和arr2交集为[2,3]
function jiaoji(setA,setB){
var s=new Set();//新建一个Set,用于存放最后的结果
for(let i of setB){//遍历setB
if(setA.has(i)){
s.add(i);//如果setA中含有setB的元素,把他放到新set中
}
}
return s;//我们以set形式返回
}
//差集:arr2和arr3的差集为[2,8,4,5,6],去掉交集
function chaji(setA,setB){
var s1=jiaoji(setA,setB);//求arr2和arr3的交集[3]
var s2=new Set(setA),s3=new Set(setB);
var s=new Set([...s2,...s3]);//setA和setB合并后去掉一个交集[2,3,8,4,5,6]
s1.forEach(function(key,value){//遍历交集
if(s.has(value)){//如果s中含有交集的元素,删除
s.delete(value);
}
});
return s;
}
//并集:arr1和arr3的并集为[1,2,3,4,5,6]
function bingji(setA,setB){
var s1=new Set(setA),s2=new Set(setB);
return new Set([...s1,...s2]);
}
//补集:arr1和arr3的补集为[1,2],arr3和arr1的补集是[5,6]
function buji(setA,setB){//属于setA不属于setB
var s1=new Set(setA),s2=new Set(setB);
for(let value of s2){
if(s1.has(value)){
s1.delete(value);
}
}
return s1;
}
console.log([...jiaoji(set1,set2)]);
console.log([...chaji(set2,set3)]);
console.log([...bingji(set1,set3)]);
console.log([...buji(set1,set3)]);
console.log([...buji(set3,set1)]);
使用Set达到数组的交差并补操作
最新推荐文章于 2022-07-07 12:05:28 发布