如何比较元素结构不同的对象数组,筛选目标数组中不匹配的对象?
解决不同结构对象数组的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
zoraentirely - They only consider two objects a "match" if both their
xandyvalues are identical - They return all objects from
arr1that don't have any matchingx/ypairs inarr2
内容的提问来源于stack exchange,提问作者Nikicatz
相关产品推荐
相关产品推荐

