Nikicatz
Nikicatz

Reputation: 105

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

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.

Upvotes: 0

Views: 1971

Answers (2)

cvetanov
cvetanov

Reputation: 373

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.

Upvotes: 2

Burgan
Burgan

Reputation: 900

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);

Upvotes: 0

Related Questions