其他分享
首页 > 其他分享> > es5,es6jQuery的差集,补集,并集,交集

es5,es6jQuery的差集,补集,并集,交集

作者:互联网

1.es5

var arr1 = [1, 2, 3, 5, 9, 7, 4]
        var arr2 = [1, 2, 3, 10, 20, 5, 4]

        // 交集
        var intersec = arr1.filter(val => arr2.indexOf(val) > -1)
        console.log(intersec)

        // 并集
        var union = arr1.concat(arr2.filter(function(val) {
            return !(arr1.indexOf(val) > -1)
        }))

        console.log(union)

        // 差集   arr2 相对于 arr1 没有的
        let diff = arr1.filter(function(val) {
            return arr2.indexOf(val) === -1
        })
        console.log(diff)

        // 补集  两个数组各自没有的
        let complement = arr1.filter(function(val) {
                return !(arr2.indexOf(val) > -1)
            })
            .concat(arr2.filter(function(val) {
                return !(arr1.indexOf(val) > -1)
            }))
        console.log(complement)

2.es6

1, 2, 3, 4, 5]
        var arr4 = [5, 6, 7, 8, 9]
        var set1 = new Set(arr3)
        var set2 = new Set(arr4)

        // 交集
        var j = arr3.filter(item => set2.has(item))
        console.log(j)

        // 并集
        // var b = Array.from(new Set([...arr3, ...arr4]))
        var b = Array.from([...set1, ...set2])
        console.log(b)

        // 补集
        var bj = [...arr3.filter(item => !set2.has(item)), ...arr4.filter(item => !set1.has(item))]
        console.log(bj)

        // 差集
        var c = arr3.filter(item => !set2.has(item))
        console.log(c)

3.jquery

var arr5 = [5, 6, 9, 7, 8, 2, 3]
        var arr6 = [2, 6, 5, 4, 10, 11, 6]

        // 交集
        let intersec = $(arr5).filter(arr6).toArray()
        console.log(intersec)

        // 补集
        let complement = $(arr5).not(arr6).toArray().concat($(arr6).not(arr5).toArray())
        console.log(complement)

        // 差集
        let diff = $(arr5).not(arr6).toArray()
        console.log(diff)

 

标签:es5,console,log,并集,补集,filter,item,val,var
来源: https://www.cnblogs.com/qianxiaoPro/p/15623904.html