简体   繁体   English

如何将数组分组/展平为子数组的所有组合

[英]How to group/flatten array into all combinations of sub-arrays

Wondering how to take a nested array such as this: 想知道如何采用这样的嵌套数组:

var arr = [
    1,
    [ 
        2, 3, 4, 
        [ 
            5, 6, 7, 8, 
            [ 9, 10 ], 
            [ 11, 12 ]
        ], 
        [ 13, 14 ] 
    ] 
]   

And apply a grouping function: 并应用分组功能:

function group(arr) {

}

Such that it converts arr into the following: 这样它将arr转换为以下内容:

var output = [
  [1, 2, 5, 13, 9, 11],
  [1, 2, 5, 13, 9, 12],
  [1, 2, 5, 13, 10, 11],
  [1, 2, 5, 13, 10, 12]

  [1, 3, 5, 13, 9, 11],
  [1, 3, 5, 13, 9, 12],
  [1, 3, 5, 13, 10, 11],
  [1, 3, 5, 13, 10, 12],

  [1, 3, 6, 13, 9, 11],
  [1, 3, 6, 13, 9, 12],
  [1, 3, 6, 13, 10, 11],
  [1, 3, 6, 13, 10, 12],

  [1, 3, 7, 13, 9, 11],
  [1, 3, 7, 13, 9, 12],
  [1, 3, 7, 13, 10, 11],
  [1, 3, 7, 13, 10, 12],

  ...

  [1, 4, 5, 13, 9, 11],
  [1, 4, 5, 13, 9, 12],
  [1, 4, 5, 13, 10, 11],
  [1, 4, 5, 13, 10, 12],

  ...
]

Basically it flattens the array, or you could say gets every combination of all sub arrays, and returns them in a flat list. 基本上,它使数组变平,或者可以说获取所有子数组的每个组合,然后将它们返回到平面列表中。 Breaking my head on this one. 我在这头上摔了个头。

Looks pretty simple - you want to apply the cartesian product on all of the nesting levels, and recursively flatten the elements. 看起来非常简单-您想在所有嵌套级别上应用笛卡尔积 ,然后递归展平元素。

However, your input is a bit weird, it would have been easier (and more flexible!) if you had used 但是,您的输入有点奇怪,如果您使用过的话,会更容易(更灵活!)

var arr = [
    [ 1 ],
    [
        [ 2, 3, 4 ],
        [
            [ 5, 6, 7, 8 ],
            [ 9, 10 ],
            [ 11, 12 ]
        ],
        [ 13, 14 ]
    ]
];

So now it requires some slicing to split the two parts of each array: 因此,现在需要进行切片以拆分每个数组的两个部分:

function flatten(arr) { return [].concat(...arr); }
function group(arr) {
    const i = arr.findIndex(Array.isArray)
    return i < 0
      ? arr
      : cartesian([arr.slice(0, i), ...arr.slice(i).map(group)]).map(flatten);
}

With the flexible input format, it would be just 有了灵活的输入格式,这将仅仅是

function group(arr) {
  return arr.every(Array.isArray) // or even Array.isArray(arr[0])?
    ? cartesian(arr.map(group)).map(flatten) // group simply every element - even the first
    : arr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM