其他分享
首页 > 其他分享> > JS 求交集,并集,差集,子集 forEach和es6两种方法

JS 求交集,并集,差集,子集 forEach和es6两种方法

作者:互联网

1.并集: [A B C R U ]


        let set111 = new Set(["A", "B", "C"])
        let set222 = new Set(["A", "R", "U"])

        let unionset = new Set();

        set111.forEach((ele) => {
            if (!unionset.has(ele)) {
                unionset.add(ele)
            }
        })

        set222.forEach((ele) => {
            if (!unionset.has(ele)) {
                unionset.add(ele)
            }
        })

        console.log(unionset);
        
        //es6
        let union = new Set([...set111, ...set222]);
        console.log(union);     

2.交集: [A ]

    let differtset = new Set();
    set111.forEach((ele) => {
        if (set222.has(ele)) {
            differtset.add(ele)
        }
    })

    console.log(differtset);

    //es6
    let intersect = new Set([...set111].filter(x => set222.has(x)));
    console.log(intersect);

3.差集

// set111 - set222 [ B C]

    // let set111 = new Set(["A","B","C"])
    // let set222 = new Set(["A","R","U"])

    let chaset = new Set();

    set111.forEach((ele) => {
        if (!set222.has(ele)) {
            chaset.add(ele)
        }
    })

    console.log(chaset);

    //es6
    let difference = new Set([...set111].filter(x => !set222.has(x)));
    console.log(difference);

标签:es6,Set,并集,差集,ele,set111,let,set222,new
来源: https://www.cnblogs.com/ddyx/p/16078419.html