我必须检索仅存在于阵列B上但在阵列A上不存在的值。
从我的研究来看,它被称为:
B中A的相对补充
数组中的值可能不是原始的。我需要一个有效且功能性的应用程序来解决这个问题。 我找到了lodash _.without函数,但它只支持原始数组。
数组A:
[{ id: 1 }, { id:2 }]数组B:
[{ id:2 }, { id:3 }]结果应该是:
[{ id:3 }]此对象是唯一存在于阵列B上的对象,但不存在于阵列A上。
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
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.
最满意答案
你可以使用一个比较函数,它接受两个对象并检查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);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);
更多推荐
发布评论