How to dynamically combine all provided arrays using JavaScript?

When working with arrays in JavaScript, you might need to generate all possible combinations from multiple arrays. This is commonly known as the Cartesian product of arrays.

Suppose we have two arrays of literals like these:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
console.log('Array 1:', arr1);
console.log('Array 2:', arr2);
Array 1: [ 'a', 'b', 'c' ]
Array 2: [ 'd', 'e', 'f' ]

We need a JavaScript function that takes multiple arrays and builds all possible combinations from them. For these two arrays, we want to get combinations like 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'.

Using Recursive Approach

Here's a recursive solution that works with any number of arrays:

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));
[
  'ad', 'ae', 'af',
  'bd', 'be', 'bf',
  'cd', 'ce', 'cf'
]

How It Works

The algorithm uses recursion to build combinations step by step:

  1. combinePart function takes a partial combination and current array index
  2. For each element in the current array, it creates a new partial combination
  3. If the combination is complete (length equals number of arrays), it adds to results
  4. Otherwise, it recursively processes the next array

Working with Three Arrays

The function works with any number of arrays:

const arr1 = ['a', 'b'];
const arr2 = ['1', '2'];
const arr3 = ['x', 'y'];

console.log(combineArrays(arr1, arr2, arr3));
[
  'a1x', 'a1y', 'a2x',
  'a2y', 'b1x', 'b1y',
  'b2x', 'b2y'
]

Alternative: Using reduce()

Here's a more functional approach using reduce():

const combineArraysReduce = (...arrays) => {
    return arrays.reduce((acc, curr) => {
        const result = [];
        acc.forEach(a => {
            curr.forEach(c => {
                result.push(a + c);
            });
        });
        return result;
    });
};

const arr1 = ['a', 'b'];
const arr2 = ['1', '2'];
console.log(combineArraysReduce(arr1, arr2));
[ 'a1', 'a2', 'b1', 'b2' ]

Conclusion

The recursive approach provides a clean solution for generating Cartesian products of multiple arrays. It handles any number of input arrays and builds all possible combinations efficiently.

Updated on: 2026-03-15T23:19:00+05:30

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements