js 集合Set的一些应用

1.数组去重

    let arr = [1,2,3,4,5,4,3,2,1], arr2 = [4,5,6,5,6];
    // 1.数组去重
    let res = [...new Set(arr)];
    console.log(res);

2.交集

    // 2.交集
    let res = [...new Set(arr)].filter(item => {
        let s2 = new Set(arr2);//4 5 6
        if(s2.has(item)) return true;
        else return false;
    });
    let res = [...new Set(arr)].filter(item => new Set(arr2).has(item));//简写
    console.log(res)

3.并集

    // 3.并集
    let res = [...new Set([...arr,...arr2])];
    console.log(res);

4.差集

    // 4.差集
    let diff = [...new Set(arr)].filter(item => !(new Set(arr2).has(item)));
    console.log(diff);

 

posted @ 2021-09-25 22:59  jerryfish  阅读(87)  评论(0编辑  收藏  举报