JavaScript：数组的交集、并集、差集、补集

样例

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); //[ 2, 4 ]

//差集
var difference = arr1.filter(function(v){ return arr2.indexOf(v) == -1 });
console.log(difference); //[ 1, 3, 5 ]

//补集
var complementary = arr1.filter(function(v){ return !(arr2.indexOf(v) > -1) })
.concat(arr2.filter(function(v){ return !(arr1.indexOf(v) > -1)}));
console.log(complementary); //[ 1, 3, 5, 6, 8, 10 ]

//并集
var union = arr1.concat(arr2.filter(function(v){ return !(arr1.indexOf(v) > -1)}));
console.log(union); //[ 1, 2, 3, 4, 5, 6, 8, 10 ]


方法二：对 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]));


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客