美文网首页
json数组实现交集,差集,并集

json数组实现交集,差集,并集

作者: 六月_1af7 | 来源:发表于2021-03-02 20:27 被阅读0次
var arr1 = [
    {
        id: 1,
        name: '11'
    },
    {
        id: 2,
        name: '22'
    },
    {
        id: 3,
        name: '3'
    }
]
var arr2 = [
    {
        id: 2,
        name: '222'
    },
    {
        id: 4,
        name: '444'
    },
    {
        id: 5,
        name: '555'
    }
]
// 两个数组的并集,并去重
function getUnion(arr1, arr2, key) {
    let result = []
    let temp = {}
    let source = [...arr1, ...arr2]
    for (let index = 0; index < source.length; index++) {
        const element = source[index];
        if (!temp[element[key]]) {
            result.push(element)
            temp[element[key]] = true
        }
    }
    return result
}
console.log(getUnion(arr1, arr2, 'id'))
// 两个数组的交集,以arr1为主
function intersection(arr1, arr2, key) {
    let keyList = arr2.map(item => item[key])
    return arr1.filter(item => keyList.includes(item[key]))
}
console.log(difference(arr1, arr2, 'id'))
// 两个数组的差集,以arr1为主
function difference(arr1, arr2, key) {
    let keyList = arr2.map(item => item[key])
    return arr1.filter(item => !keyList.includes(item[key]))
}
console.log(difference(arr1, arr2, 'id'))

相关文章

网友评论

      本文标题:json数组实现交集,差集,并集

      本文链接:https://www.haomeiwen.com/subject/kiixqltx.html