0

I have these two arrays :

array1 = [{firstname: 'abc', age: 24}];

array2 = [{name: 'bcg', age: 33}, {name:'abc', age: 55}];

I want to loop through both arrays and remove the object from the second array (array 2) that has a the same name key value as the first object in array 1. So essentially loop through both arrays to see where key values match and then remove the relevant object array2[1] from the second array.

I tried doing this but it did not work:

for (let p = 0; p < array1.length; p++) {
  for (let i = 0; i < array2.length; i++) {
    if (array1[p].firstname === array2[i].name) {
      array2.splice(i,1);
    }
  }
}

Is there a way this can work with JavaScript ?

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
Deji James
  • 367
  • 6
  • 20
  • How many objects will the first array contain? – Andy Jun 16 '22 at 17:41
  • Does this answer your question? [Filter array of objects with another array of objects](https://stackoverflow.com/questions/31005396/filter-array-of-objects-with-another-array-of-objects) – pilchard Jun 16 '22 at 17:45
  • also: [Filter array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filter-array-of-objects-based-on-another-array-in-javascript) combined with [Convert array of objects to array of strings](https://stackoverflow.com/questions/38913343/convert-array-of-objects-to-array-of-strings) – pilchard Jun 16 '22 at 17:49

2 Answers2

4

You can simply achieve it by just using Array.filter() along with Set.has() method.

Live Demo :

const array1 = [{firstname: 'abc', age: 24}];

const array2 = [{name: 'bcg', age: 33}, {name:'abc', age: 55}];

const namesArr = new Set(array1.map(obj => obj.firstname));

const res = array2.filter(({ name }) => !namesArr.has(name));

console.log(res);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
2

You can achieve this with Array#filter in conjunction with Array#some.

const array1 = [{firstname: 'abc', age: 24}], array2 = [{name: 'bcg', age: 33}, {name:'abc', age: 55}];
let res = array2.filter(x => !array1.some(y => y.firstname === x.name));
console.log(res);

For increased performance with a larger amount of data, you can construct a Set to store all the names in the first array and lookup each name in constant time.

const array1 = [{firstname: 'abc', age: 24}], array2 = [{name: 'bcg', age: 33}, {name:'abc', age: 55}];
let names1 = new Set(array1.map(x => x.firstname));
let res = array2.filter(x => !names1.has(x.name));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80