如何在N个可变长度的JavaScript数组中生成所有值的组合?
假设我有N个JavaScript数组,例如
var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third = ['f', 'g', 'h', 'i', 'j'];
Run Code Online (Sandbox Code Playgroud)
(在这个例子中有三个数组,但它有N个数组用于解决问题.)
我想输出它们的所有值的组合,以产生
aef
aeg
aeh
aei
aej
bef
beg
....
dej
Run Code Online (Sandbox Code Playgroud)
编辑:这是我工作的版本,使用ffriend接受的答案作为基础.
var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length ===1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var …Run Code Online (Sandbox Code Playgroud) 我需要获取数组的所有可能子集.
说我有这个:
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我怎么得到这个?
[], [1], [2], [1, 2], [2, 3], [1, 3], [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我对所有子集感兴趣.有关特定长度的子集,请参阅以下问题: