How to dynamically combine all provided arrays using JavaScript?


Suppose we have two arrays of literals like these −

const arr1= ['a', 'b', 'c'];
const arr2= ['d', 'e', 'f'];

We are required to write a JavaScript function that takes in two such arrays and build all possible combinations from the arrays.

So, for these two arrays, the output should look like −

const output = [ad, ae, af, bd, be, bf, cd, ce, cf];

Example

The code for this will be −

const arr1= ['a', 'b', 'c'];
const arr2= ['d', 'e', 'f'];
const combineArrays = (...arr) => {
   const res = [];
   const combinePart = (part, index) => {
      arr[index].forEach(el => {
         const p = part.concat(el);
         if(p.length === arr.length){
            res.push(p.join(''));
            return;
         };
         combinePart(p, index + 1);
      });
   };
   combinePart([], 0);
   return res;
}
console.log(combineArrays(arr1, arr2));

Output

And the output in the console will be −

[
   'ad', 'ae', 'af',
   'bd', 'be', 'bf',
   'cd', 'ce', 'cf'
]

Updated on: 23-Nov-2020

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements