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
CodePudding user response:
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);
CodePudding user response:
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.