EN
JavaScript - all possible combinations for 2D array items
9 points
In this article, we would like to show how to create combinations for 2D array items.
Simple visualisation:
xxxxxxxxxx
1
// input:
2
3
[
4
['a', 'b', 'c'],
5
['1', '2'],
6
['w', 'x', 'y', 'z']
7
]
8
9
10
// output:
11
12
a 1 w
13
a 1 x
14
a 1 y
15
a 1 z
16
a 2 w
17
a 2 x
18
a 2 y
19
a 2 z
20
b 1 w
21
b 1 x
22
b 1 y
23
b 1 z
24
b 2 w
25
b 2 x
26
b 2 y
27
b 2 z
28
c 1 w
29
c 1 x
30
c 1 y
31
c 1 z
32
c 2 w
33
c 2 x
34
c 2 y
35
c 2 z
Quick solution:
xxxxxxxxxx
1
function detectCombinations(input, output, position, path) {
2
if (position == null) {
3
position = 0;
4
}
5
if (path == null) {
6
path = [];
7
}
8
if (position < input.length) {
9
var item = input[position];
10
for (var i = 0; i < item.length; ++i) {
11
var value = item[i];
12
path.push(value);
13
detectCombinations(input, output, position + 1, path);
14
path.pop();
15
}
16
} else {
17
output.push(path.slice());
18
}
19
};
20
21
22
// Helper methods:
23
24
function printArray(array) {
25
for (var i = 0; i < array.length; ++i) {
26
console.log(array[i].join(' '));
27
}
28
};
29
30
31
// Usage example:
32
33
var input = [
34
['a', 'b', 'c'],
35
['1', '2'],
36
['w', 'x', 'y', 'z']
37
];
38
var output = [];
39
40
detectCombinations(input, output);
41
printArray(output);