<script>
let arr1 = [
{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
{fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"}
];
let arr2 = [
{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
];
let arrtemp = arr2.map((item) => {
return item.fpcid;
});
let json = arr1.find((item) => {
return !arrtemp.includes(item.fpcid);
});
console.log(json);
</script>
这样可以快速找出arr1比arr2多的第一个对象,如果要找出所有对象,可以将find改为filter
另有一种嵌套方法,性能较差
<script>
let arr1 = [
{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
{fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"}
];
let arr2 = [
{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
];
let json = arr1.find((item) => {
let flag = true;
arr2.forEach((value) => {
if (item.fpcNameCode == value.fpcNameCode) {
flag = false;
}
});
return flag;
});
console.log(json);
</script>
性能测试
<script>
let arr1 = [
{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
{fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"}
];
let arr2 = [
{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
];
let i = 0;
while (i < 10000) {
arr1.push({fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"});
arr2.push({fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"});
i++;
}
let t1 = new Date().getTime();
let arrtemp = arr2.map((item) => {
return item.fpcid;
});
let json = arr1.filter((item) => {
return !arrtemp.includes(item.fpcid);
});
let t2 = new Date().getTime();
console.log(t2 - t1); //4
console.log(json);
let t3 = new Date().getTime();
let json1 = arr1.filter((item) => {
let flag = true;
arr2.forEach((value) => {
if (item.fpcNameCode == value.fpcNameCode) {
flag = false;
}
});
return flag;
});
let t4 = new Date().getTime();
console.log(t4 - t3); //900
console.log(json1);
</script>