如何通过比较对象的两个数组和对象中的不同元素来过滤数组? [英] How to filter array by comparing two arrays of objects with different elements in their objects?
问题描述
如何通过比较对象中两个具有不同元素的对象数组来过滤数组? 我有:
How to filter array by comparing two arrays of objects with different elements in their objects? I have:
arr1 =[{ x: 1, y: 2, z:3 }, { x: 2, y: 1, z:4 }];
arr2 = [{ x: 1, y: 2, a:5 }, { x: 2, y: 3, a:4 }];
我想比较两个数组中的x和y值,并从第一个数组中返回非宏对象,在上面的示例中,返回[{ x: 2, y: 1, z:4 }]
我尝试使用_.differenceWith(arr1, arr2, _.isEqual);
,但是显然,数组应该具有类似的对象,而我不是这种情况.
I want to compare x and y values from both arrays and return the not macthing object from first array, in the above example return [{ x: 2, y: 1, z:4 }]
I tried to use _.differenceWith(arr1, arr2, _.isEqual);
but obviously for this the arrays should have similar objects which is not my case.
推荐答案
您非常接近正确的答案.
lodash的_.differenceWith
函数具有三个参数,要检查的数组,要排除的值,第三个参数是确定所需值的比较器.在您的情况下,使用_.isEqual
查找完全相同的对象(据我了解,这不是您想要的行为).
You are very close to the right answer.
The _.differenceWith
function from lodash has three arguments, the array to inspect, the values to exclude and the third argument is a comparator which determines which values you need. In your case, using _.isEqual
is looking for exactly the same object (which as far as I understood is not your desired behavior).
如果只关心具有相同的x
和y
值,请尝试使用自定义比较器,而不是lodash的_.isEqual
函数.
If you only care about having same x
and y
values, try using your custom comparator instead of the _.isEqual
function from lodash.
它看起来像这样:
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 }];
// this is your custom comparator which is called with each value from the two arrays
// I gave descriptive names to the arguments so that it is more clear
const customComparator = (valueFromFirstArray, valueFromSecondArray) =>
valueFromFirstArray.x === valueFromSecondArray.x
&& valueFromFirstArray.y === valueFromSecondArray.y;
const result = _.differenceWith(arr1, arr2, customComparator);
console.log(result);
// will print [{x: 2, y: 1, z: 4}]
或者,如果您不熟悉箭头功能,则可以这样声明自定义比较器:
Or if you are not familiar with arrow functions, the custom comparator can be declared like this:
function customComparator(valueFromFirstArray, valueFromSecondArray) {
return valueFromFirstArray.x === valueFromSecondArray.x
&& valueFromFirstArray.y === valueFromSecondArray.y
}
这是一个小提琴,您可以在其中与自定义比较器混合
Here is a fiddle where you can mingle around with the custom comparator if you'd like to.
这篇关于如何通过比较对象的两个数组和对象中的不同元素来过滤数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!