let a = [1, 2, 3, 4, 5]
let b = [2, 4, 6, 8, 10]
//交集
let c = a.filter(function (v) {
return b.indexOf(v) > -1
})
//差集
let d = a.filter(function (v) {
return b.indexOf(v) == -1
})
//补集
let e = a.filter(function (v) {
return !(b.indexOf(v) > -1)
})
.concat(b.filter(function (v) {
return !(a.indexOf(v) > -1)
}))
//并集
let f = a.concat(b.filter(function (v) {
return !(a.indexOf(v) > -1)
}));
console.log('交集', c) // [2, 4]
console.log('差集', d) // [1, 3, 5]
console.log('补集', e) // [1, 3, 5, 6, 8, 10]
console.log('并集', f) // [1, 2, 3, 4, 5, 6, 8, 10]
2、ES6 语法实现
使用扩展运算符(...)以及 Set 的特性实现
// 交集
let c = a.filter(x => new Set(b).has(x));
// 差集
let d = a.filter(x => !new Set(b).has(x));
// 补集
let e = [...a.filter(x => !new Set(b).has(x)), ...b.filter(x => !new Set(a).has(x))];
// 并集
let f = Array.from(new Set([...a, ...b]));
3、对 Array 进行扩展
//数组迭代函数
Array.prototype.each = function(fn) {
fn = fn || Function.K;
let a = [];
let args = Array.prototype.slice.call(arguments, 1);
for (let i = 0; i < this.length; i++) {
let res = fn.apply(this, [this[i], i].concat(args));
if (res != null) a.push(res);
}
return a;
};
//数组是否包含指定元素
Array.prototype.contains = function(suArr) {
for (let i = 0; i < this.length; i++) {
if (this[i] == suArr) {
return true;
}
}
return false;
}
//不重复元素构成的数组
Array.prototype.uniquelize = function() {
let ra = new Array();
for (let 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('交集', Array.intersect(a, b)) // [2, 4]
console.log('差集', Array.minus(a, b)) // [1, 3, 5]
console.log('补集', Array.complement(a, b)) // [1, 3, 5, 6, 8, 10]
console.log('并集', Array.union(a, b)) // [1, 2, 3, 4, 5, 6, 8, 10]
1、使用
filter
、indexOf
、concat
2、
ES6
语法实现3、对
Array
进行扩展