Vijay Thopate
Vijay Thopate

Reputation: 73

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?

Upvotes: 0

Views: 2654

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386604

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

Upvotes: 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)

Upvotes: 0

R4ncid
R4ncid

Reputation: 7129

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)

Upvotes: 4

Related Questions