如何在 JavaScript 中获得两个集合的并集

在 JavaScript 中获取两个集合的并集

How to get the Union of Two Sets in JavaScript

要获得两个 Set 的并集,请使用扩展语法 (…) 将 Set 的值解压缩到数组中并将结果传递给Set()构造函数,例如
new Set([...set1, ...set2]). 新的Set将包含其他两个的联合。

索引.js
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const union = new Set([...set1, ...set2]); console.log(union); // 👉️ {'a', 'b', 'c', 'd'}

我们使用
扩展语法 (…)
将两个对象的值解包
Set到一个数组中。

索引.js
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const arr = [...set1, ...set2]; console.log(arr); // 👉️ ['a', 'b', 'c' ,'a', 'b', 'd']

该数组存储重复值而不是Set. 一旦将数组传递给Set()构造函数,所有重复项都将被忽略。

The
Set()
constructor takes an iterable object as a parameter, so an array is perfect.

Get a Union of Two Sets using for of loop #

To get a union of two Sets, pass the first Set to the Set() constructor to
create a third Set. Then use the for...of loop to iterate over the second
Set and add each element to the newly created Set. The new Set will
contain a union of the other two Sets.

index.js
function getUnion(setA, setB) { const union = new Set(setA); for (const element of setB) { union.add(element); } return union; } const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); console.log(getUnion(set1, set2)); // 👉️ {'a', 'b', 'c', 'd'}

We created a reusable function that returns the union of two Sets.

The first step is to create a new Set from the first Set.

Then, we used the
for…of
loop to iterate over the second Set and add its values to the new Set.

集合不存储重复值,所以我们不必担心处理它。