Home > Net >  Loop through 2 arrays to find index of where object keys match and then delete that object
Loop through 2 arrays to find index of where object keys match and then delete that object

Time:06-17

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 ?

CodePudding user response:

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

CodePudding user response:

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

  • Related