Open In App

How to cartesian product of 2 arrays using JavaScript ?

The task is to compute the cartesian product of two JavaScript arrays with the help of JavaScript. Here are a few techniques discussed. 

Approach 1:



Example: This example implements the above approach. 




const arr1 = [
    [13, 'G'],
    [16, 'C']
];
 
const arr2 = [
    [8, 'F'],
    [36, 'P']
];
 
let res = "";
 
function CartesianProduct() {
    let ans = [];
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            ans.push(arr1[i].concat(arr2[j]));
        }
    }
 
    res = "";
     
    for (let i = 0; i < ans.length; i++) {
        res = res + "[" + ans[i] + "]\n";
    }
    console.log(res);
}
 
CartesianProduct();

Output

[13,G,8,F]
[13,G,36,P]
[16,C,8,F]
[16,C,36,P]

Approach 2:

Example: This example implements the above approach.




const arr1 = [
    [13, 'G'],
    [16, 'C']
];
 
const arr2 = [
    [8, 'F'],
    [36, 'P']
];
 
let res = "";
 
function CartesianProduct() {
    let ans = [].concat.apply([], arr1.map(
        arr1 => (arr2.map(arr2 => arr1.concat(arr2)))));
 
    res = "";
 
    for (let i = 0; i < ans.length; i++) {
        res = res + "[" + ans[i] + "]\n";
    }
    console.log(res);
}
 
CartesianProduct();

Output
[13,G,8,F]
[13,G,36,P]
[16,C,8,F]
[16,C,36,P]


Article Tags :