Friday, November 14, 2025
HomeLanguagesJavascriptHow to cartesian product of 2 arrays using JavaScript ?

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:

  • Create a new array.
  • Traverse the first array by the outer loop and the second array by the inner loop.
  • In the inner loop, Concatenate the first array element with the second array element and push it into a new array.

Example: This example implements the above approach. 

Javascript




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:

  • Create a new array.
  • The same approach is followed here, for every element of the first array, every element of the second array is concatenated and pushed to the new array with the help of apply() and map() methods.

Example: This example implements the above approach.

Javascript




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]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7142 POSTS0 COMMENTS
Thapelo Manthata
6837 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS