Languages

JavaScript - print all combinations of 2D array items

11 points
Asked by:
Marcin
18490

Hi, maybe my problem is simple, how to write program that prints all combinations of the sub-arrays items (each sub-array has different size).

My data:

// ONLINE-RUNNER:browser;

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

// for ... for ... for ... ?

As result I whould like to get:

a 1 w <------------------ a 1
a 1 x
a 1 y
a 1 z
a 2 w <------------------   2
a 2 x
a 2 y
a 2 z
b 1 w <------------------ b 1
b 1 x
b 1 y
b 1 z
b 2 w <------------------   2
b 2 x
b 2 y
b 2 z
c 1 w <------------------ c 1
c 1 x
c 1 y
c 1 z
c 2 w <------------------   2
c 2 x
c 2 y
c 2 z
1 answer
3 points
Answered by:
Marcin
18490

Try this solution:

// ONLINE-RUNNER:browser;

function printCombinations(array, position, result) {
    if (position < array.length) {
    	var item = array[position];
		for (var i = 0; i < item.length; ++i) {
			printCombinations(array, position + 1, result + " " + item[i]);
		}
	} else {
        console.log(result.substring(1));
	}
}

// Usage example:

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

printCombinations(array, 0, '');
0 comments Add comment
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join