样例
var arr1 = [1,2,3,4,5];
var arr2 = [2,4,6,8,10];
方法一:使用 filter、concat 来计算
var intersection = arr1.filter(function(v){ return arr2.indexOf(v) > -1 });
console.log(intersection);
var difference = arr1.filter(function(v){ return arr2.indexOf(v) == -1 });
console.log(difference);
var complementary = arr1.filter(function(v){ return !(arr2.indexOf(v) > -1) })
.concat(arr2.filter(function(v){ return !(arr1.indexOf(v) > -1)}));
console.log(complementary);
var union = arr1.concat(arr2.filter(function(v){ return !(arr1.indexOf(v) > -1)}));
console.log(union);
方法二:对 Array 进行扩展
Array.prototype.each = function(fn){
fn = fn || Function.K;
var a = [];
var args = Array.prototype.slice.call(arguments, 1);
for(var i = 0; i < this.length; i++){
var res = fn.apply(this,[this[i],i].concat(args));
if(res != null) a.push(res);
}
return a;
};
Array.prototype.contains = function(suArr){
for(var i = 0; i < this.length; i ++){
if(this[i] == suArr){
return true;
}
}
return false;
}
Array.prototype.uniquelize = function(){
var ra = new Array();
for(var i = 0; i < this.length; i ++){
if(!ra.contains(this[i])){
ra.push(this[i]);
}
}
return ra;
};
Array.intersect = function(a, b){
return a.uniquelize().each(function(o){return b.contains(o) ? o : null});
};
Array.minus = function(a, b){
return a.uniquelize().each(function(o){return b.contains(o) ? null : o});
};
Array.complement = function(a, b){
return Array.minus(Array.union(a, b),Array.intersect(a, b));
};
Array.union = function(a, b){
return a.concat(b).uniquelize();
};
console.log("a与b的交集:", Array.intersect(a, b));
console.log("a与b的差集:", Array.minus(a, b));
console.log("a与b的补集:", Array.complement(a, b));
console.log("a与b的并集:", Array.union(a, b));
方法三:ES6
var sa = new Set(a);
var sb = new Set(b);
let intersect = a.filter(x => sb.has(x));
let minus = a.filter(x => !sb.has(x));
let complement = [...a.filter(x => !sb.has(x)), ...b.filter(x => !sa.has(x))];
let unionSet = Array.from(new Set([...a, ...b]));