Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create every combination possible for the contents of two arrays in JavaScript
Creating every possible combination from two arrays is known as a Cartesian product. This involves pairing each element from the first array with every element from the second array.
Problem Setup
Given two arrays of literals:
const arr1 = ["A","B","C"];
const arr2 = ["1","2","3"];
console.log("Array 1:", arr1);
console.log("Array 2:", arr2);
Array 1: [ 'A', 'B', 'C' ] Array 2: [ '1', '2', '3' ]
We need to create all possible combinations by pairing each element from the first array with each element from the second array.
Using Nested Loops
The most straightforward approach uses nested for loops to iterate through both arrays:
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));
[ 'A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3' ]
Using Array Methods (flatMap)
A more functional approach using flatMap() and map():
const arr1 = ["A","B","C"];
const arr2 = ["1","2","3"];
const cartesianProduct = (arr1, arr2) => {
return arr1.flatMap(item1 =>
arr2.map(item2 => item1 + item2)
);
};
console.log(cartesianProduct(arr1, arr2));
[ 'A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3' ]
Creating Object Pairs
Instead of concatenating strings, you can create object pairs:
const letters = ["A","B"];
const numbers = [1,2,3];
const createObjectPairs = (arr1, arr2) => {
const result = [];
for(let i = 0; i < arr1.length; i++){
for(let j = 0; j < arr2.length; j++){
result.push({ letter: arr1[i], number: arr2[j] });
}
}
return result;
};
console.log(createObjectPairs(letters, numbers));
[
{ letter: 'A', number: 1 },
{ letter: 'A', number: 2 },
{ letter: 'A', number: 3 },
{ letter: 'B', number: 1 },
{ letter: 'B', number: 2 },
{ letter: 'B', number: 3 }
]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Nested Loops | Clear | Fast | Large arrays, simple operations |
| flatMap/map | Functional | Good | Small to medium arrays, complex transformations |
Conclusion
Creating Cartesian products is essential for generating all possible combinations from two arrays. Use nested loops for simplicity and performance, or functional methods like flatMap() for more expressive code.
