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

106
Views
How to get unique element from two arrays in js?

I'm trying to get unique (by id) values from two arrays.

But it returns whole array instead of { id: 3 }

const a = [{ id: 1 }, { id: 2 }];
const b = [{ id: 1 }, { id: 2 }, { id: 3 }];
    
const array3 = b.filter((obj) => a.indexOf(obj) == -1);
    
console.log(array3);

What's wrong here?

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

0

You cannot compare objects you should check that an element with that id doesn't exists in the other array

here I used some that returns a boolean if he can find a match

const a = [{
  id: 1
}, {
  id: 2
}];
const b = [{
  id: 1
}, {
  id: 2
}, {
  id: 3
}];

const array3 = b.filter(obj => !a.some(({id}) => obj.id === id));

console.log(array3)

about 4 years ago · Juan Pablo Isaza Report

0

In your case, the following code gives all unique objects as an array, based on the id.

const a = [{
  id: 1
}, {
  id: 2
}];
const b = [{
  id: 1
}, {
  id: 2
}, {
  id: 3
}];

const array3 = b.filter(objB => a.some((objA) => objB.id !== objA.id));

console.log(array3)
about 4 years ago · Juan Pablo Isaza Report

0

A different approach with a symmetrically result.

const
    take = m => d => o => m.set(o.id, (m.get(o.id) || 0) + d),
    a = [{ id: 1 }, { id: 2 }],
    b = [{ id: 1 }, { id: 2 }, { id: 3 }],
    map = new Map(),
    add = take(map),
    result = [];
    
a.forEach(add(1));
b.forEach(add(-1));
map.forEach((v, id) => v && result.push({ id }));
    
console.log(result);

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!