Generating combinations from n arrays with m elements in JavaScript


We are required to write a JavaScript function that generates combinations from n number of arrays with m number of elements in them.

For example −

Consider this data −

const arr = [
   [0,1],
   [0,1,2,3],
   [0,1,2]
]

3 sub arrays, with a different number of elements in them.

What we want to do is get all combinations by combining an item from each array.

For example −

0,0,0 // item 0 from array 0, item 0 from array 1, item 0 from array 2
0,0,1
0,0,2
0,1,0
0,1,1
0,1,2
0,2,0
0,2,1
0,2,2

And so on.

If the number of arrays were fixed, it would be easy to make a hard-coded implementation. But the number of arrays may vary −

const arr1 = [[0,1], [0,1]];
const arr2 = [[0,1,3,4], [0,1], [0], [0,1]];

Example

The code for this will be −

const arr = [
   [0,1],
   [0,1,2,3],
   [0,1,2]
]
const combineAll = (array) => {
   const res = [];
   let max = array.length−1;
   const helper = (arr, i) => {
      for (let j=0, l=array[i].length; j<l; j++) {
         let copy = arr.slice(0);
         copy.push(array[i][j]);
         if (i==max)
         res.push(copy);
         else
         helper(copy, i+1);
      };
   };
   helper([], 0);
   return res;
};
console.log(combineAll(arr));

And the output in the console will be −

[
   [ 0, 0, 0 ], [ 0, 0, 1 ],
   [ 0, 0, 2 ], [ 0, 1, 0 ],
   [ 0, 1, 1 ], [ 0, 1, 2 ],
   [ 0, 2, 0 ], [ 0, 2, 1 ],
   [ 0, 2, 2 ], [ 0, 3, 0 ],
   [ 0, 3, 1 ], [ 0, 3, 2 ],
   [ 1, 0, 0 ], [ 1, 0, 1 ],
   [ 1, 0, 2 ], [ 1, 1, 0 ],
   [ 1, 1, 1 ], [ 1, 1, 2 ],
   [ 1, 2, 0 ], [ 1, 2, 1 ],
   [ 1, 2, 2 ], [ 1, 3, 0 ],
   [ 1, 3, 1 ], [ 1, 3, 2 ]
]

Updated on: 21-Nov-2020

610 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements