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
Compute cartesian product of elements in an array in JavaScript
The Cartesian product of two sets (arrays) A and B, denoted A × B, is the set (array) of all ordered pairs (a, b) where a is in A and b is in B.
In simpler terms, a cartesian product of two arrays is a permutation of all possible arrays of two elements whose first element belongs to the first array and the second element belongs to the second array.
Example of Cartesian Product
If the two arrays are:
const arr1 = [1, 2, 3]; const arr2 = [4, 5];
Then their cartesian product will be:
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
Using Nested Loops
The most straightforward approach uses nested loops to iterate through both arrays:
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const cartesianProduct = (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(cartesianProduct(arr1, arr2));
[ [ 1, 4 ], [ 1, 5 ], [ 2, 4 ], [ 2, 5 ], [ 3, 4 ], [ 3, 5 ] ]
Using flatMap() Method
A more modern approach uses the flatMap() method for a functional programming style:
const arr1 = ['A', 'B'];
const arr2 = [1, 2, 3];
const cartesianProduct = (arr1, arr2) => {
return arr1.flatMap(x => arr2.map(y => [x, y]));
};
console.log(cartesianProduct(arr1, arr2));
[ [ 'A', 1 ], [ 'A', 2 ], [ 'A', 3 ], [ 'B', 1 ], [ 'B', 2 ], [ 'B', 3 ] ]
Cartesian Product of Multiple Arrays
For computing cartesian product of multiple arrays, you can use a recursive approach:
const cartesianMultiple = (...arrays) => {
return arrays.reduce((acc, curr) => {
return acc.flatMap(x => curr.map(y => [...x, y]));
}, [[]]);
};
const result = cartesianMultiple([1, 2], ['a', 'b'], [10, 20]);
console.log(result);
[ [ 1, 'a', 10 ], [ 1, 'a', 20 ], [ 1, 'b', 10 ], [ 1, 'b', 20 ], [ 2, 'a', 10 ], [ 2, 'a', 20 ], [ 2, 'b', 10 ], [ 2, 'b', 20 ] ]
Comparison of Methods
| Method | Readability | Performance | Multiple Arrays |
|---|---|---|---|
| Nested Loops | Good | Fast | Complex |
| flatMap() | Excellent | Moderate | Easy with reduce() |
Conclusion
The cartesian product combines all elements from multiple arrays into ordered pairs. Use nested loops for performance-critical applications or flatMap() for cleaner, more readable code.
