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).
If you only care about having same x
and y
values, try using your custom comparator instead of the _.isEqual
function from lodash.
It would look something like this:
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.