EN
TypeScript - all possible combinations for 2D array items
0 points
In this article, we would like to show how to create combinations for 2D array items.
xxxxxxxxxx
1
const detectCombinations = (input: string[][], output: string[][], position?: number, path?: string[]): void => {
2
if (position == null) {
3
position = 0;
4
}
5
if (path == null) {
6
path = [];
7
}
8
if (position < input.length) {
9
const item = input[position];
10
for (let i = 0; i < item.length; ++i) {
11
const 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
// Helper methods:
22
23
const printArray = (array: string[][]): void => {
24
for (let i = 0; i < array.length; ++i) {
25
console.log(array[i].join(' '));
26
}
27
};
28
29
// Usage example:
30
31
const input: string[][] = [
32
['a', 'b', 'c'],
33
['d', 'e'],
34
['w', 'x', 'y', 'z'],
35
];
36
37
const output: string[][] = [];
38
39
detectCombinations(input, output);
40
printArray(output);
Output:
xxxxxxxxxx
1
a 1 w
2
a 1 x
3
a 1 y
4
a 1 z
5
a 2 w
6
a 2 x
7
a 2 y
8
a 2 z
9
b 1 w
10
b 1 x
11
b 1 y
12
b 1 z
13
b 2 w
14
b 2 x
15
b 2 y
16
b 2 z
17
c 1 w
18
c 1 x
19
c 1 y
20
c 1 z
21
c 2 w
22
c 2 x
23
c 2 y
24
c 2 z