- js 实现数组的集合运算
为了方便测试我们这里使用nodejs,代码如set_operation.js
// 去重
function array_remove_repeat(a) {
var r = [];
for(var i = 0; i < a.length; i ++) {
var flag = true;
var temp = a[i];
for(var j = 0; j < r.length; j ++) {
if(temp === r[j]) {
flag = false;
break;
}
}
if(flag) {
r.push(temp);
}
}
return r;
}
// 交集
function array_intersection(a, b) {
var result = [];
for(var i = 0; i < b.length; i ++) {
var temp = b[i];
for(var j = 0; j < a.length; j ++) {
if(temp === a[j]) {
result.push(temp);
break;
}
}
}
return array_remove_repeat(result);
}
// 并集
function array_union(a, b) {
return array_remove_repeat(a.concat(b));
}
// 差集 a - b
function array_difference(a, b) {
//clone = a
var clone = a.slice(0);
for(var i = 0; i < b.length; i ++) {
var temp = b[i];
for(var j = 0; j < clone.length; j ++) {
if(temp === clone[j]) {
//remove clone[j]
clone.splice(j,1);
}
}
}
return array_remove_repeat(clone);
}
a = [1,2,3,4,5];
b = [3,4,5,6,7];
c = array_intersection(a, b);
d = array_union(a, b);
e = array_difference(a, b);
f = array_difference(b, a);
console.log("test array a:", a, " b:", b);
console.log("a & b :", c);
console.log("a + b :", d);
console.log("a - b:", e);
console.log("b - a:", f);
- 测试
我们这里使用nodejs来测试
测试结果:
stephen@stephen:~/openstack/demo/nodejs$ node set_operation.js
test array a: [ 1, 2, 3, 4, 5 ] b: [ 3, 4, 5, 6, 7 ]
a & b : [ 3, 4, 5 ]
a + b : [ 1, 2, 3, 4, 5, 6, 7 ]
a - b: [ 1, 2 ]
b - a: [ 6, 7 ]
标签:并集,temp,示例,++,clone,差集,length,var,array
From: https://www.cnblogs.com/css2020/p/17269173.html