Set 的合集 并集 差集

合集

var   arr1 = [1,2,3,3,5,4,7];
var   arr2 = [2,3,6];
function union() {
    //先将数组去重
     let  s1 = new  Set(arr1);
     let  s2 = new  Set(arr2);
     //[...s1,...s2] 先将两个数组合并为一个数组 
     // 去重 new  Set([...s1,...s2])
     // 将集合变成数组 [...array]
     let  allUnion = [...new  Set([...s1,...s2])];
     console.log(allUnion);
}
union();

先声明两个数组 

var   arr1 = [1,2,3,3,5,4,7];
var   arr2 = [2,3,6];

创建一个函数 调用这个函数

function union() {
   
}
union();

合集首先里面的数组是没有 重复的 我们先将 各自的数组去重 

 let  s1 = new  Set(arr1);
     let  s2 = new  Set(arr2);

将去重后的数组合并

[...s1,...s2]

这个时候我们得到的数组里面 可能有重复的

比如 arr1  去重后得到 [1,2,3,4,5,7], arr2 去重后 的数组为 [2,3,6]

合并数组得到 [1,2,3,4,5,7,2,3,6]  数组里面有重复的 所以我们将 这个数组再次去重 

 let  allUnion = [...new  Set([...s1,...s2])];
将集合变成数组的操作是       [...array]
 
 
输出 结果:
[ 1, 2, 3, 5, 4, 7, 6 ]
 
并集
function Bing () {
     let  s1 = new  Set(arr1);
     let  s2 = new  Set(arr2);
     let  s3 = [...s1].filter(item=>{
         return   s2.has(item)
     });
     console.log(s3);
}
Bing ();

使用 filter 函数进行过滤 符合或者不符合 的情况 

has 函数可以用来 判断集合是否有某个 数值 

输出 :

[ 2, 3 ]
 
差集 
 
function Chai() {
    let  s1 = new  Set(arr1);
    let  s2 = new  Set(arr2);
    let  s3 = [...s1].filter(item=>{
        return  !s2.has(item)
    });
    console.log(s3);
}
Chai();

输出 :

[ 1, 5, 4, 7 ]
 
 
 
原文地址:https://www.cnblogs.com/guangzhou11/p/11327085.html