【问题标题】:Merge array of Sets into single Set将集合数组合并为单个集合
【发布时间】:2018-07-17 08:47:35
【问题描述】:

如果我有一组 Set,将这些 Set 组合成一个 Set 的最佳方法是什么?

说如果我有这个数组:

const array = [new Set([1, 2, 3]), new Set([4, 5, 6]), new Set([7, 8, 9])]

我将如何操作此数组以生成具有相同输出的单个 Set:

new Set([1,2,3,4,5,6,7,8,9])

这个数组有任意数量的任意大小的集合。

【问题讨论】:

  • 你有没有尝试过?
  • new Set([...array[0], ...array[1], ...array[2]])?
  • 我尝试使用扩展运算符new Set(...array),但它只扩展了第一个集合。我尝试在 array.map 中使用扩展运算符,但一直遇到问题。 new Set(array.map(set => ...set)) 给我错误Uncaught SyntaxError: Unexpected token ...
  • @D.Wood Spread syntax 仅适用于数组字面量。它不是产生值的运算符。
  • @Bergi 啊,我现在明白了。谢谢!

标签: javascript


【解决方案1】:

你也可以使用reduce

new Set( array.reduce( ( a, c ) => a.concat( [...c] ), [] ) )

演示

var array = [new Set([1, 2, 3]), new Set([4, 5, 6]), new Set([7, 8, 9])];
var output = new Set( array.reduce( ( a, c ) => a.concat( [...c] ), [] ) );
console.log( [...output] );

【讨论】:

  • 注意:执行 [...c] 将消除 "c" 数组中的重复条目,
  • @A.T.无论如何它都会发生,因为预计输出会进入Set,并且无论如何它都会消除所有重复的条目。
  • @A.T.不,重复项已被消除,因为cSet。传播它并没有什么不同。
  • [...output] 实际上是将Set 转换为数组。您可以遍历集合 keys()values() 但更容易将其转换为数组控制台输出它
【解决方案2】:

最简单的就是最好的:

let result = new Set;
for (const set of array)
    for (const element of set)
        result.add(element);

或者,如果您想使用构造函数,我会使用立即调用的生成器函数来创建迭代器:

const result = new Set(function* () {
    for (const set of array)
        yield* set;
}());

当然你也可以为此声明reusable functional-minded generator function

function* flatten(iterable) {
    for (const inner of iterable)
        for (const element of inner)
            yield element;
}
const result = new Set(flatten(array));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-20
    • 2023-03-07
    • 1970-01-01
    • 2018-09-22
    • 2021-03-29
    • 2017-03-07
    • 1970-01-01
    • 2021-02-12
    相关资源
    最近更新 更多