Javascript中二维数组的所有可能组合 [英] All possible combinations of a 2d array in Javascript

查看:36
本文介绍了Javascript中二维数组的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个用可变长度数组填充的可变长度数组.像这样的东西,例如:

So I have a variable length array filled with variable length arrays. Something like this for example:

var arr2d = [
    ['red', 'blue'],
    ['cotton','polyester','silk'],
    ['large','medium','small']
]

我正在尝试从每个数组中获取一个的所有可能组合.所以答案应该是这样的:

I am trying to get all possible combinations of one from each array. so the answer should look something like this:

var answer = [
    ['red', 'cotton', 'large'],
    ['red', 'cotton', 'medium'],
    ['red', 'cotton', 'small'],
    ['red', 'polyester', 'large'],
    .
    .
    .
]

我已经查看了有关此主题的其他答案,但所有答案都在 Java 中(我需要 javascript)并且他们正在寻找所有组合,而不仅限于 length === arr2d.length 的组合.我已经看了将近 2 个小时,但仍然想不出递归地执行此操作的方法.这是头部爆炸场景之一,因为两个数组的长度都不同(我有一个这些二维数组的数组,我必须获得组合).在我列出的示例中,只有 18 种可能性,但实际上可能有数千种.

I've looked into the other answer on this topic but all of them are in java (I need javascript) and they were looking for all combinations and not limited to the combinations of length === arr2d.length. I've looked at this for almost 2 hours and still I cannot think of a way to do this recursively. It's one of those head explosion scenarios because both the arrays vary in length (I have an array of these 2d arrays that I must get the combinations for). In the example I've laid out there are only 18 possiblities, but in practice it could be thousands.

推荐答案

使用递归函数时的另一个选择是在函数的参数中维护您的状态.这可以有时使函数更容易理解:

Another option when using recursive functions is to maintain your state in the arguments of the function. This can sometimes make the function easier to understand:

var arr2d = [['red', 'blue'],['cotton','polyester','silk'],['large','medium','small']]

function combos(list, n = 0, result = [], current = []){
    if (n === list.length) result.push(current)
    else list[n].forEach(item => combos(list, n+1, result, [...current, item]))
 
    return result
}

console.log(combos(arr2d))

这篇关于Javascript中二维数组的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆