# JavaScript数组系列问题：数组差集

JavaScript求出两个数组的差集，下面是我实现的方法

``````function arrayDiffSet(a, b) {

if ((!a || !a.length) && (b && b.length)) {
return b
} else if ((!b || !b.length) && (a && a.length)) {
return a
}

var aMap = {},
_aMap = {},
_bMap = {};

for (var i = 0, length = a.length; i < length; i++) {
aMap[a[i]] = _aMap[a[i]] = true;
}

for (var i = 0, length = b.length; i < length; i++) {
if (aMap[b[i]]) {
delete _aMap[b[i]];
} else {
_bMap[b[i]] = true;
}
}

return {
a: Object.keys(_aMap),
b: Object.keys(_bMap)
}

}

function generateRandomArray(length, range) {
var result = [];
for (var i = 0; i < length; i++) {
result[result.length] = Math.floor(Math.random() * range);
}
return result
}

var a = generateRandomArray(5, 10);
var b = generateRandomArray(10, 10);

console.log('a', a);
console.log('b', b);

console.time('start');
console.log(arrayDiffSet(a, b));
console.timeEnd('start');
``````

----------但是这个方法还有下面两点：
1、扩展性差，如果我需要返回的差集不去重，那需要再重新写一个方法；
2、没有办法对对象数组求差集；

2 个回答

• 1.3k

``````var a = generateRandomArray(5, 10);
var b = generateRandomArray(10, 10);

// 不去重
var result = {
a: a.filter(el => !b.includes(el)),
b: b.filter(el => !a.includes(el))
}

// 去重
var result2 = {
a: [...new Set(a)].filter(el => !b.includes(el)),
b: [...new Set(b)].filter(el => !a.includes(el))
}

// 合并一下
function diffSet(a, b, noDup) {
if (noDup) {
a = [...new Set(a)];
b = [...new Set(b)];
}
return {
a: a.filter(el => !b.includes(el)),
b: b.filter(el => !a.includes(el))
}
}``````

### 不使用ES6:

``````// 不去重
// 使用indexOf代替includes

a.filter(function(el){
return b.indexOf(el) == -1;
});

// 去重
// 引入index先对a自身去重

a.filter(function(el, idx){
return a.indexOf(el) == idx && b.indexOf(el) == -1;
});``````