Warm tip: This article is reproduced from serverfault.com, please click

typescript-从多个对象数组生成组合

(typescript - Generating combinations from multiple Arrays of object)

发布于 2020-11-27 23:34:16

我有数组:[{key: 1, value: 1}, {key: 2, value:2}, {key: 3, value: 3}] 另一个数组:[[{key: 1, value: 12}, {key: 1, value: 13}], [{key: 2, value: 21}], [{key: 4, value:4}, {key: 5, value: 5}]]

我想生成结果数组为:

[
[{key: 1, value: 1}, {key: 2, value:2}, {key: 3, value: 3}, {key: 4, value:4}, {key: 5, value: 5}], 
[{key: 1, value: 12}, {key: 2, value:2}, {key: 3, value: 3}, {key: 4, value:4}, {key: 5, value: 5}], 
[{key: 1, value: 13}, {key: 2, value:2}, {key: 3, value: 3}, {key: 4, value:4}, {key: 5, value: 5}], 
[{key: 1, value: 1}, {key: 2, value:21}, {key: 3, value: 3}, {key: 4, value:4}, {key: 5, value: 5}], 
[{key: 1, value: 12}, {key: 2, value:21}, {key: 3, value: 3}, {key: 4, value:4}, {key: 5, value: 5}], 
[{key: 1, value: 13}, {key: 2, value:21}, {key: 3, value: 3}, {key: 4, value:4}, {key: 5, value: 5}]
]

我能够使用reduce + concat生成array2的组合。

const array2 = [[{key: 1, value: 12}, {key: 1, value: 13}], [{key: 2, value: 21}], [{key: 4, value:4}], [{key: 5, value: 5}]];

const combinations = array2.reduce((accumulator, current) =>
      accumulator.reduce((objAccumulator, currentObj) =>
        objAccumulator.concat(
          current.map(obj => [].concat(currentObj, obj))), []));
          
console.log(combinations);

但我无法找到一个好的/优化的解决方案来获得最终结果。任何帮助,将不胜感激。

Questioner
avinash chavan
Viewed
11
Yunhai 2020-11-28 11:22:53

我尝试将我的想法添加到评论中,但是空间不够。

不知道你实际上有什么限制。可能你可以列出所有数组中的所有可能性,然后在以后进行所有组合以减少时间复杂度。

例如,将所有值从输入数组转换为映射,如下所示

{
  //I highly suggest use a set here instead of a list so you don't need to 
  //worry about duplicate number while adding new values
  1: [1, 12 ,13],
  2: [2, 21],
  3: [3],
  4: [4],
  5: [5],
}

那么你可以合并数组中的所有值,而这已经是过去的答案: JavaScript-从具有m个元素的n个数组中生成组合

从理论上讲,这是最好的解决方案,因为你只有额外的O(所有数组大小的总和)+组合成本,在这种情况下,我认为你无法减少太多空间。