求数组对象的交集,并集,补集
var a=[ {id:'001',name:'product01'}, {id:'002',name:'product02'}, {id:'003',name:'product03'}, {id:'004',name:'product04'}, {id:'005',name:'product05'} ];
var b=[ {id:'003',name:'product03'}, {id:'006',name:'product06'}, {id:'007',name:'product07'}, {id:'008',name:'product08'}, ];
求交集
let intersectionData=[]
a.map((val) => {
b.filter((item) => {
if (
item.id === val.id
) {
data.push(item);
}
});
});
console.log(intersectionData)
第二种方法在掘金的文章下改进的
var obj = {};
var arr = a.concat(b);
arr.filter((item) => {
obj.hasOwnProperty(item.id) ? intersectionData.push(item) : (obj[item.id] = true);
});
console.log(intersectionData)
求并集
求并集就是两个数组对象合并
let tempArr = [].concat(a, b);
let unionData=setDuplicateRemoval(tempArr)
//数组对象去重
setDuplicateRemoval(data) {
let result = [];
let obj = {};
for (let i = 0; i < data.length; i++) {
if (!obj[data[i].id]) {
result.push(data[i]);
obj[data[i].id] = true;
}
}
return result;
},
},
console.log(unionData)
补集
let complementData=[]
tempArr.filter((v) => {
//如果子集每一个都没有与父集对应的indexId就会返回false 不回添加到参数里面代表已经有的且重复的不回添加进来
if (intersectionData.every((item) => item.indexId !== v.indexId)) {
complementData.push(v)
}
});Ï
console.log(complementData)