-
斯蒂芬大帝
如果不知道这是否最有效,但也许是最短的A = [1, 2, 3, 4];B = [1, 3, 4, 7];diff = A.filter(function(x) { return B.indexOf(x) < 0 })console.log(diff);已更新至ES6:A = [1, 2, 3, 4];B = [1, 3, 4, 7];diff = A.filter(x => !B.includes(x) );console.log(diff);
-
鸿蒙传说
console.clear();let a = new Set([1, 2, 3, 4]);let b = new Set([5, 4, 3, 2]);let a_minus_b = new Set([...a].filter(x => !b.has(x)));let b_minus_a = new Set([...b].filter(x => !a.has(x)));let a_intersect_b = new Set([...a].filter(x => b.has(x))); console.log([...a_minus_b]) // {1}console.log([...b_minus_a]) // {5}console.log([...a_intersect_b]) // {2,3,4}
-
烙印99
您可以将对象用作地图,以避免线性扫描B每个元素,A如user187291的答案:function setMinus(A, B) {
var map = {}, C = [];
for(var i = B.length; i--; )
map[B[i].toSource()] = null; // any other value would do
for(var i = A.length; i--; ) {
if(!map.hasOwnProperty(A[i].toSource()))
C.push(A[i]);
}
return C;}非标准toSource()方法用于获取唯一的属性名称; 如果所有元素都已经具有唯一的字符串表示(如数字的情况),则可以通过删除toSource()调用来加速代码。