Computing the Cartesian Product of Multiple Arrays in JavaScript


We are required to write a JavaScript function that takes in multiple arrays of numbers. The function should return an array of the cartesian product of the elements from all the arrays.

For example −

If the input arrays are −

[1, 2], [10, 20], [100, 200, 300]

Then the output should be −

const output = [
   [ 1, 10, 100 ],
   [ 1, 10, 200 ],
   [ 1, 10, 300 ],
   [ 1, 20, 100 ],
   [ 1, 20, 200 ],
   [ 1, 20, 300 ],
   [ 2, 10, 100 ],
   [ 2, 10, 200 ],
   [ 2, 10, 300 ],
   [ 2, 20, 100 ],
   [ 2, 20, 200 ],
   [ 2, 20, 300 ]
];

Example

const arr1 = [1, 2];
const arr2 = [10, 20];
const arr3 = [100, 200, 300];
const cartesianProduct = (...arr) => {
   return arr.reduce((acc,val) => {
      return acc.map(el => {
         return val.map(element => {
            return el.concat([element]);
         });
      }).reduce((acc,val) => acc.concat(val) ,[]);
   }, [[]]);
};
console.log(cartesianProduct(arr1, arr2, arr3));

Output

This will produce the following output −

[
   [ 1, 10, 100 ], [ 1, 10, 200 ],
   [ 1, 10, 300 ], [ 1, 20, 100 ],
   [ 1, 20, 200 ], [ 1, 20, 300 ],
   [ 2, 10, 100 ], [ 2, 10, 200 ],
   [ 2, 10, 300 ], [ 2, 20, 100 ],
   [ 2, 20, 200 ], [ 2, 20, 300 ]
]

Updated on: 31-Mar-2023

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements