B中A与函数规划的相对补集

时间:2018-01-15 08:32:51

标签: javascript

我必须检索仅存在于阵列B上但在阵列A上不存在的值。

从我的研究中,它被称为:

  

relative complement of A in B

enter image description here

数组中的值可能不是原始的。我需要一个有效且功能性的应用程序来解决这个问题。 我找到了lodash _.without函数,但它只支持基元数组。

数组A:

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

数组B:

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

结果应为:

[{
    id:3
}]

此对象是阵列B上唯一存在的对象,但不存在于阵列A上。

4 个答案:

答案 0 :(得分:2)

你可以使用一个比较函数来获取两个对象,并检查id是否存在不平等。

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);

检查平等性

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);

答案 1 :(得分:1)

您可以将array#filterarray#some一起使用。迭代arrB并使用arrA检查id是否包含array#some,并否定array#some的结果。

var arrA = [{id: 1},{id:2}],
    arrB = [{id:2},{id:3}],
    result = arrB.filter(({id}) => !arrA.some(o => o.id === id));
console.log(result);

答案 2 :(得分:0)

您可以使用array.prototype.filterarray.prototype.findIndex

var arrayA = [{ id: 1 }, { id: 2 }];
var arrayB = [{ id: 2 }, { id: 3 }];

var result = arrayB.filter(b => arrayA.findIndex(a => a.id === b.id) === -1);
console.log(result);

答案 3 :(得分:0)

如果你想使用 lodash,_.differenceBy 可能有用:

relativeComplementOfAinB = _.differenceBy(arrayB, arrayA, v => v.id);