Set 的妙用

作者:xie392地址:https://v.douyin.com/iem4sRs7/更新时间:2024-12-21

案例代码

1
/**
2
* 两个数组的并集、交集、差集
3
* 不能出现重复选项,得到的结果是一个新数组
4
*/
5
const arr1 = [32, 22, 55, 33, 11, 33, 5]
6
const aee2 = [22, 55, 77, 88, 88, 99, 99]
7
8
// 并集
9
const union = [...new Set([...arr1, ...aee2])]
10
11
// 交集
12
const intersection = [...new Set(arr1.filter(x => aee2.includes(x)))]
13
14
// 差集
15
const difference = [...new Set(arr1.filter(x => !aee2.includes(x)))]
16
17
console.log(union)
18
console.log(intersection)
19
console.log(difference)

输出结果:

1
[
2
32, 22, 55, 33, 11,
3
5, 77, 88, 99
4
]
5
[ 22, 55 ]
6
[ 32, 33, 11, 5 ]