南猫猫猫猫猫

导航

JS数组的交集、差集、并集、补集 (使用 ES6 语法实现)--转载

1,实现原理

而在 ES6 中我们可以借助扩展运算符(…)以及 Set 的特性实现相关计算,代码也会更加简单些。

2,样例代码

var a = [1,2,3,4,5]
var b = [2,4,6,8,10]
console.log("数组a:", a);
console.log("数组b:", b);
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]));
console.log("a与b的交集:", intersect);
console.log("a与b的差集:", minus);
console.log("a与b的补集:", complement);
console.log("a与b的并集:", unionSet);

 

 

 

 

https://blog.csdn.net/weixin_44021910/article/details/104637568

posted on 2021-07-14 20:00  南猫猫猫猫猫  阅读(242)  评论(0编辑  收藏  举报