I have to retrieve the values that exist only on Array B, but do not exist on Array A.
From my research, It is called:
Values in the arrays may not be primitives.I need an efficient and functional apporach to this problem.
I have found lodash _.without
function, but it supports only array of primitive numbers.
Array A:
JavaScript
x
7
1
[{
2
id: 1
3
},
4
{
5
id:2
6
}]
7
Array B:
JavaScript
1
7
1
[{
2
id:2
3
},
4
{
5
id:3
6
}]
7
result should be:
JavaScript
1
4
1
[{
2
id:3
3
}]
4
this object is the only one who exist on Array B, but not on Array A.
Advertisement
Answer
You could use a comparison function which takes two objects and check the id
for unequalness.
JavaScript
1
6
1
var aa = [{ id: 1 }, { id: 2 }],
2
bb = [{ id: 2 }, { id: 3 }],
3
comparison = (a, b) => a.id !== b.id,
4
result = bb.filter(b => aa.every(a => comparison(a, b)));
5
6
console.log(result);
With a check for equalness
JavaScript
1
6
1
var aa = [{ id: 1 }, { id: 2 }],
2
bb = [{ id: 2 }, { id: 3 }],
3
comparison = (a, b) => a.id === b.id,
4
result = bb.filter(b => aa.every(a => !comparison(a, b)));
5
6
console.log(result);