You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何比较元素结构不同的对象数组,筛选目标数组中不匹配的对象?

解决不同结构对象数组的x/y值匹配问题

Got it, I totally get why _.differenceWith(arr1, arr2, _.isEqual) didn't work for you—since it checks for full object equality, including every property, your objects with extra properties (z vs a) will never be considered equal, even if their x and y values match.

Here's how to fix this by focusing only on the x and y properties we care about:

Option 1: Using Lodash with a custom comparator

We can pass a custom comparison function to _.differenceWith that only checks if x and y are the same between two objects:

const arr1 = [{ x: 1, y: 2, z:3 }, { x: 2, y: 1, z:4 }];
const arr2 = [{ x: 1, y: 2, a:5 }, { x: 2, y: 3, a:4 }];

// Custom comparator: only check x and y values
const matchXY = (objFromArr1, objFromArr2) => {
  return objFromArr1.x === objFromArr2.x && objFromArr1.y === objFromArr2.y;
};

const unmatchedObjects = _.differenceWith(arr1, arr2, matchXY);
console.log(unmatchedObjects); // Output: [{ x: 2, y: 1, z:4 }]

Option 2: Native JavaScript (no Lodash needed)

If you prefer to avoid Lodash, you can use Array.filter() combined with Array.some() to achieve the same result:

const arr1 = [{ x: 1, y: 2, z:3 }, { x: 2, y: 1, z:4 }];
const arr2 = [{ x: 1, y: 2, a:5 }, { x: 2, y: 3, a:4 }];

const unmatchedObjects = arr1.filter(obj1 => {
  // Check if there's NO object in arr2 with matching x and y
  return !arr2.some(obj2 => obj1.x === obj2.x && obj1.y === obj2.y);
});

console.log(unmatchedObjects); // Output: [{ x: 2, y: 1, z:4 }]

How this works

Both approaches do the same core thing:

  • They ignore extra properties like z or a entirely
  • They only consider two objects a "match" if both their x and y values are identical
  • They return all objects from arr1 that don't have any matching x/y pairs in arr2

内容的提问来源于stack exchange,提问作者Nikicatz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:50:58