Home
IT Knowledge
Inspiration
Languages
EN

# JavaScript - all possible combinations for 2D array items

9 points
Created by:
28980

In this article we would like to show hw to create combinations for 2D array items.

// input:

[
['a', 'b', 'c'],
['1', '2'],
['w', 'x', 'y', 'z']
]

// output:

a 1 w
a 1 x
a 1 y
a 1 z
a 2 w
a 2 x
a 2 y
a 2 z
b 1 w
b 1 x
b 1 y
b 1 z
b 2 w
b 2 x
b 2 y
b 2 z
c 1 w
c 1 x
c 1 y
c 1 z
c 2 w
c 2 x
c 2 y
c 2 z

Quick solution:

// ONLINE-RUNNER:browser;

function detectCombinations(input, output, position, path) {
if (position == null) {
position = 0;
}
if (path == null) {
path = [];
}
if (position < input.length) {
var item = input[position];
for (var i = 0; i < item.length; ++i) {
var value = item[i];
path.push(value);
detectCombinations(input, output, position + 1, path);
path.pop();
}
} else {
output.push(path.slice());
}
};

// Helper methods:

function printArray(array) {
for (var i = 0; i < array.length; ++i) {
console.log(array[i].join(' '));
}
};

// Usage example:

var input = [
['a', 'b', 'c'],
['1', '2'],
['w', 'x', 'y', 'z']
];
var output = [];

detectCombinations(input, output);
printArray(output);

1. JavaScript - all possible combinations tree for 2D array items