#### All possible combinations of a 2d array in Javascript

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

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

2 个回复

` `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))` `

` `const arr2d = [ ['red', 'blue'], ['cotton', 'polyester', 'silk'], ['large', 'medium', 'small'] ]; function combinations(arr) { if (arr.length === 0) return [[]]; let res = [], [first, ...rest] = arr; let remaining = combinations(rest); first.forEach(e => { remaining.forEach(smaller => { res.push([e].concat(smaller)); }); }); return res; } console.log(combinations(arr2d));` `

1 JavaScript 中二维数组的 forEach() 和 Apply() 方法

2016-01-12 15:27:41 5 16985   foreach
2 二维数组的所有可能组合[重复]

3 Java中二维数组的总和

4 C中二维数组的排序

5 C中二维数组的“方向”

2009-05-01 19:45:39 8 1784   c/ arrays
6 PHP中二维数组的总和

7 C中二维数组的大小

2013-06-24 20:21:26 2 15190   c/ sizeof
8 C中二维数组的大小

2015-02-20 09:24:36 2 123   c
9 java中二维数组的问题

10 Python中二维数组的对数

2019-02-15 10:51:42 5 95   python