How to create every combination possible for the contents of two arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have two arrays of literals like this −

const arr1 = ["A","B","C"];
const arr2 = ["1","2","3"];

We are required to write a JavaScript function that takes in two such arrays of literals. The function should then combine each element of the first array with each element of the second array and push them into a new array.

Therefore, the output for the above input should look like this −

const output = ["A1","A2","A3","B1","B2","B3","C1","C2","C3"];

Example

The code for this will be −

const arr1 = ["A","B","C"];
const arr2 = ["1","2","3"];
const prepareCartesian = (arr1 = [], arr2 = []) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      for(let j = 0; j < arr2.length; j++){
         res.push(arr1[i] + arr2[j])
      }
   };
   return res;
};
console.log(prepareCartesian(arr1, arr2));

Output

And the output in the console will be −

[
   'A1', 'A2', 'A3',
   'B1', 'B2', 'B3',
   'C1', 'C2', 'C3'
]
raja
Updated on 21-Nov-2020 09:45:46

Advertisements