Dash separated cartesian product of any number of arrays in JavaScript

We need to write a JavaScript function that takes any number of arrays and computes their cartesian product, with elements separated by dashes. The cartesian product combines every element from the first array with every element from the second array, and so on.

What is Cartesian Product?

The cartesian product of two or more sets is the set of all possible combinations where we pick one element from each set. For example, if we have arrays ['a', 'b'] and ['1', '2'], the cartesian product would be ['a-1', 'a-2', 'b-1', 'b-2'].

Implementation

Here's how we can implement this using the reduce method:

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

const dotCartesian = (...arrs) => {
    const res = arrs.reduce((acc, val) => {
        let ret = [];
        acc.map(obj => {
            val.map(obj_1 => {
                ret.push(obj + '-' + obj_1);
            });
        });
        return ret;
    });
    return res;
};

console.log(dotCartesian(arr1, arr2, arr3));
[
  'a-1-x', 'a-1-y', 'a-2-x',
  'a-2-y', 'a-3-x', 'a-3-y',
  'b-1-x', 'b-1-y', 'b-2-x',
  'b-2-y', 'b-3-x', 'b-3-y',
  'c-1-x', 'c-1-y', 'c-2-x',
  'c-2-y', 'c-3-x', 'c-3-y',
  'd-1-x', 'd-1-y', 'd-2-x',
  'd-2-y', 'd-3-x', 'd-3-y'
]

How It Works

The function uses the reduce method to iterate through all input arrays. For each array, it combines every element from the accumulator with every element from the current array, joining them with a dash. The process continues until all arrays are processed.

Alternative Implementation

Here's a more readable version using nested loops:

const cartesianProduct = (...arrays) => {
    if (arrays.length === 0) return [];
    if (arrays.length === 1) return arrays[0];
    
    let result = arrays[0];
    
    for (let i = 1; i < arrays.length; i++) {
        const temp = [];
        for (const item1 of result) {
            for (const item2 of arrays[i]) {
                temp.push(item1 + '-' + item2);
            }
        }
        result = temp;
    }
    
    return result;
};

console.log(cartesianProduct(['A', 'B'], ['1', '2'], ['x']));
['A-1-x', 'A-2-x', 'B-1-x', 'B-2-x']

Conclusion

Both implementations create the cartesian product by combining elements from multiple arrays with dash separators. The reduce method provides a functional approach, while the loop-based version offers better readability for complex scenarios.

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

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements