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'))
网友评论