JS数组的交集、并集、差集,数组去重,获取两个数组重复的元素,去除两个数组相同的元素

        let arr1=[1,2,3,4,5,6]
        let arr2=[4,5,6,7,8,9]
        // 并集 数组去重 
        let RemoveSame=[...new Set([...arr1,...arr2])]
        console.log(RemoveSame) //[1, 2, 3, 4, 5, 6, 7, 8, 9]

        //数组交集,或得两个数组重复的元素
        let SamePart=arr1.filter(item=>arr2.includes(item))
        console.log(SamePart) //[4, 5, 6]

        //差集=并集-交集  去除两个数组相同的元素
        let Difference=RemoveSame.filter(item=>!SamePart.includes(item))
        console.log(Difference) //[1, 2, 3, 7, 8, 9]

猜你喜欢

转载自www.cnblogs.com/lwming/p/11717396.html
今日推荐