Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
Loop through 2 arrays to find index of where object keys match and then delete that object

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 ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!