Skip to content
Advertisement

relative complement of A in B with functional programming

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:

relative complement of A in B

enter image description here

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:

[{
    id: 1
},
{
    id:2
}]

Array B:

[{
    id:2
},
{
    id:3
}]

result should be:

[{
    id:3
}]

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.

var aa = [{ id: 1 }, { id: 2 }],
    bb = [{ id: 2 }, { id: 3 }],
    comparison = (a, b) => a.id !== b.id,
    result = bb.filter(b => aa.every(a => comparison(a, b)));

console.log(result);

With a check for equalness

var aa = [{ id: 1 }, { id: 2 }],
    bb = [{ id: 2 }, { id: 3 }],
    comparison = (a, b) => a.id === b.id,
    result = bb.filter(b => aa.every(a => !comparison(a, b)));

console.log(result);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement