0

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 }];

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.

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Nikicatz
  • 105
  • 2
  • 11

2 Answers2

2

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.

cvetanov
  • 363
  • 1
  • 3
  • 12
0

Use the filter function

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 }];


let notMatched = arr2.filter(function (item, index) {
  return !(item.x === arr1[index].x && item.y == arr1[index].y);
});
console.log(notMatched);
Burgan
  • 880
  • 1
  • 7
  • 24
  • Hi Flash, thanks. But the only problem is the array lengths are not equal hence this will fail and array lengths of both arrays is not fixed and can vary. – Nikicatz May 25 '18 at 19:41