js数组的差集_JS求两个对象数组的差集先上代码:
{
let arr1 = [
{ fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34" },
{ fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33" },
{ fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35" },
{ fpcid: "2da37fdfe66140089dc3367b21cc6197", fpcNameCode: "36" }
];
let arr2 = [
{ fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34" },
{ fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33" }
]
;
function getDifferenceSetA(arr1, arr2) {
arr1 = arr1.map(JSON.stringify);
arr2 = arr2.map(JSON.stringify);
at(arr2).filter(function (v, i, arr) {
return arr.indexOf(v) === arr.lastIndexOf(v);
}).map(JSON.parse)
}
function getDifferenceSetB(arr1,arr2,typeName){
js合并两个数组
return Object.at(arr2).reduce((acc,cur) => {
if (acc[cur[typeName]] && acc[cur[typeName]][typeName] === cur[typeName]) {
delete acc[cur[typeName]];
}else{
acc[cur[typeName]] = cur;
}
return acc ;
},{}));
}
console.log('getDifferenceSetA:',getDifferenceSetA(arr1,arr2));
console.log('getDifferenceSetB:',getDifferenceSetB(arr1,arr2,'fpcid'));
}
输出结果如下图:
两种⽅案⽐较,A⽅案⽐较取巧,使⽤起来⽅便快捷,但有个问题,对于值不为基础类型的对象可能产⽣⼀些不可预知的报错;B⽅案⽐较稳定,可以适应各种对象⽐较,但写法和逻辑相对A稍微复杂点。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。