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

329
Views
Check if object of any array exist in an another array, if not exists then push onto another array , or else remove it from another array

I'm working on a checkbox ui react web app, where in, on check we dispatch items array with a object in it, and on uncheck also we dispatch items array with object in it. So I need to add this logic - Check if object of any array exist in an another array, if not exists then push onto another array , or else remove it from another array

let items1 = [{ name: "a" }, { name: "b" }, { name: "c" }];
let items2 = [{ name: "a" }, { name: "d" }, { name: "e" }];

const commonItems = items1.filter((x) => items2.some((y) => y.name === x.name));

if (!commonItems) {
    items1.push(...items2);
} else {
    items1 = items1.filter((x) => items2.some((y) => y.name !== x.name));
}

console.log(items1);
console.log(items2);

Check if object of any array exist in an another array, if not exists then push onto another array , or else remove it from another array, Is this code corect for above logic?

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

0

Couple of issues. 1) commonItems is always a truth value because filter returns empty array when no results, so always going to else block 2) Else block filter is not correct. (updated here to use !some)

let items1 = [{ name: "a" }, { name: "b" }, { name: "c" }];
let items2 = [{ name: "a" }, { name: "d" }, { name: "e" }];

const commonItems = items1.filter((x) => items2.some((y) => y.name === x.name));

console.log(commonItems)
if (commonItems.length < 1) {
    items1.push(...items2);
} else {
    items1 = items1.filter((x) => !items2.some((y) => y.name === x.name));
}

console.log(items1);
console.log(items2);

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!