-3
const character = [
  { id: 1, na: "A" },
  { id: 2, na: "B" },
  { id: 3, na: "C" },
  { id: 4, na: "D" },
  { id: 5, na: "f" },
];

const character2 = [
  { id: 3, na: "C" },
  { id: 4, na: "D" },
];

How can I get the different elements in the two arrays For example, I need items A ,B AND F

  • Welcome to [so]! Please take the [tour], visit the [help] and read up on [asking good questions](https://stackoverflow.com/help/asking). After doing some research and [searching](https://stackoverflow.com/help/searching) for related topics on SO, try it yourself. If you're stuck, post a [mcve] of your attempt and note exactly where you're stuck. People will be glad to help. – Scott Sauyet Nov 01 '22 at 17:28
  • Does this answer your question? [How to get the difference between two arrays of objects in JavaScript](https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript) – Clément Baconnier Nov 01 '22 at 17:47

2 Answers2

2

From the way you worded your question, it looks as if you're looking for a way to find all the elements in an array "A" that do not intersect with an array "B"

If that's the case, you can use array.includes

const a = [
    1,2,3
]

const b = [
    3
]

const filtered = a.filter(x => !b.includes(x))
console.log(filtered);
user3425506
  • 1,285
  • 1
  • 16
  • 26
Gage
  • 45
  • 1
  • 7
  • Comparing objects within an array will behave slightly different from comparing primitives (like strings or numbers), as they will only return true for `obj1==obj2` if both occupy the same space in memory. Having the same properties and the same values will not yield `true` in a `==` (or `===`) comparison of objects.. – Carsten Massmann Nov 01 '22 at 18:11
  • In this case, being there's an ID field in the objects which in most all cases are used for unique identification, you could compare against the ID in this case. I agree with you comparing object A === object B would not work in this case. – Gage Nov 01 '22 at 18:24
0

Another way would be to create a new Set() first and compare against its content:

const arr = [
  { id: 1, na: "A" },
  { id: 2, na: "B" },
  { id: 3, na: "C" },
  { id: 4, na: "D" },
  { id: 5, na: "F" }],
  exc = [
  { id: 3, na: "C" },
  { na: "D", id: 4 }]; // the comparison will work, regardless of the property order

// create an "exclusion object" EXO (an ES6 Set):
const exo = exc.reduce((a,{id,na})=>a.add(`${id}:${na}`), new Set());

// filter by checking against an existing set member of EXO:
const res = arr.filter(({id,na})=>!exo.has(`${id}:${na}`));

console.log(res)

This approach compares for a static set of properties, but it can easily be set up to look for varying properties too.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43