可以使用Array.filter()和Array.some()方法来解决此问题。以下是代码示例:
const arr1 = [
{ id: 1, name: "A" },
{ id: 2, name: "B" },
{ id: 3, name: "C" },
];
const arr2 = [
{ id: 2, job: "Developer" },
{ id: 3, job: "Designer" },
{ id: 4, job: "Manager" },
];
const result = arr1.filter(({ id: id1 }) =>
!arr2.some(({ id: id2 }) => id1 === id2)
);
console.log(result);
// Output: [{ id: 1, name: "A" }]
在上面的代码中,我们将两个数组arr1和arr2作为输入。我们首先使用Array.filter()函数过滤掉arr1数组中与arr2数组中任何对象的“id”值匹配的元素。这将返回一个新的数组,该数组不包含匹配的元素。我们使用Array.some()方法来检查arr2数组中是否存在与arr1数组中的元素的“id”值匹配的对象。 If any match is found, the arrow function passed to Array.some() returns true, and the arrow function passed to Array.filter() drops the matching object from the output array.
如果找到任何匹配项,则传递给Array.some()的箭头函数返回true,并传递给Array.filter()的箭头函数从输出数组中删除匹配的对象。最终,我们得到了一个新的数组result,其中仅包含arr1数组中不匹配的元素。