3 回答
TA贡献1877条经验 获得超6个赞
Set
您可以对所有值取 apro_code
并通过检查该值是否不在集合中来过滤第二个数组。
const
array1 = [{ des: "cont1", note: "cont1", pro_code: "XXY" }, { des: "cont2", note: "cont2", pro_code: "NNB" }, { des: "cont4", note: "cont4", pro_code: "QQA" }, { des: "cont5", note: "cont5", pro_code: "GFD" }],
array2 = [{ des: "cont1", note: "cont1", pro_code: "XXY" }, { des: "cont2", note: "cont2", pro_code: "NNB" }, { des: "cont3", note: "cont3", pro_code: "QAS" }],
pro_codes = new Set(array1.map(({ pro_code }) => pro_code)),
result = array2.filter(({ pro_code }) => !pro_codes.has(pro_code));
console.log(result);
TA贡献1824条经验 获得超5个赞
这是另一个优化的解决方案
const arr1 = [{
des: "cont1",
note: "cont1",
pro_code: "XXY"
}, {
des: "cont2",
note: "cont2",
pro_code: "NNB"
}, {
des: "cont4",
note: "cont4",
pro_code: "QQA"
}, {
des: "cont5",
note: "cont5",
pro_code: "GFD"
}];
const arr2 = [{
des: "cont1",
note: "cont1",
pro_code: "XXY"
}, {
des: "cont2",
note: "cont2",
pro_code: "NNB"
}, {
des: "cont3",
note: "cont3",
pro_code: "QAS"
}];
const results = arr2.filter(({ pro_code: id1 }) => !arr1.some(({ pro_code: id2 }) => id2 === id1));
console.log(results);
TA贡献1811条经验 获得超4个赞
简而言之,您的要求是过滤arr2并保留不在arr1.
const arr3 = arr2.filter(function(arr2item) {
// only keep this item if it is not in arr1
return !arr1.some(function(arr1item) {
return arr1item.pro_code === arr2item.pro_code;
})
});
const arr1 = [{des: "cont1", note: "cont1", pro_code: "XXY"}, {des: "cont2", note: "cont2", pro_code: "NNB"}, {des: "cont4", note: "cont4", pro_code: "QQA"}, {des: "cont5", note: "cont5", pro_code: "GFD"}];
const arr2 = [{des: "cont1", note: "cont1", pro_code: "XXY"}, {des: "cont2", note: "cont2", pro_code: "NNB"}, {des: "cont3", note: "cont3", pro_code: "QAS"}]
const arr3 = arr2.filter(function(arr2item) {
return !arr1.some(function(arr1item) {
return arr1item.pro_code === arr2item.pro_code;
})
});
console.log(arr3);
添加回答
举报