Filter an array containing objects based on another array containing objects in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have two arrays of objects like these −

const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];

We are required to write a JavaScript function that takes in two such arrays. Our function should return a new filtered version of the first array (arr1 in this case) that contains only those objects with a name property that are not contained in the second array (arr2 in this case) with the same name property.

Therefore, the output, in this case, should look like −

const output = [{id:'2',name:'B'},{id:'4',name:'D'}];

Example

The code for this will be −

const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
const filterByReference = (arr1, arr2) => {
   let res = [];
   res = arr1.filter(el => {
      return !arr2.find(element => {
         return element.id === el.id;
      });
   });
   return res;
}
console.log(filterByReference(arr1, arr2));

Output

And the output in the console will be −

[ { id: '2', name: 'B' }, { id: '4', name: 'D' } ]
raja
Published on 20-Nov-2020 10:36:33
Advertisements