Home > Back-end >  How to get unique element from two arrays in js?
How to get unique element from two arrays in js?

Time:05-11

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?

CodePudding user response:

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)

CodePudding user response:

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)
  • Related