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 ?

3

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@pilchard Thanks again! I updated code snippet and it's a learning for me as well.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.