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
Computing the Cartesian Product of Two Sets in JavaScript
In set theory, a Cartesian product is a mathematical operation that returns a set from multiple sets. For sets A and B, the Cartesian product A × B is the set of all ordered pairs (a, b) where a ? A and b ? B.
We need to write a JavaScript function that takes two arrays representing distinct sets and returns a 2-D array containing their Cartesian product.
What is Cartesian Product?
The Cartesian product creates all possible combinations between elements of two sets. If set A has m elements and set B has n elements, the result will have m × n ordered pairs.
Using Nested Loops
The most straightforward approach uses nested loops to iterate through both arrays and create all possible pairs:
const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8];
const cartesianProduct = (arr1 = [], arr2 = []) => {
if (!arr1 || !arr2 || !arr1.length || !arr2.length) {
return null;
}
const result = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
result.push([arr1[i], arr2[j]]);
}
}
return result;
};
console.log(cartesianProduct(arr1, arr2));
[ [ 1, 5 ], [ 1, 6 ], [ 1, 7 ], [ 1, 8 ], [ 2, 5 ], [ 2, 6 ], [ 2, 7 ], [ 2, 8 ], [ 3, 5 ], [ 3, 6 ], [ 3, 7 ], [ 3, 8 ], [ 4, 5 ], [ 4, 6 ], [ 4, 7 ], [ 4, 8 ] ]
Using Array Methods (flatMap)
A more functional approach uses flatMap() to create the Cartesian product:
const cartesianProductFunctional = (arr1, arr2) => {
if (!arr1?.length || !arr2?.length) return [];
return arr1.flatMap(a => arr2.map(b => [a, b]));
};
const set1 = ['A', 'B'];
const set2 = ['X', 'Y', 'Z'];
console.log(cartesianProductFunctional(set1, set2));
[ [ 'A', 'X' ], [ 'A', 'Y' ], [ 'A', 'Z' ], [ 'B', 'X' ], [ 'B', 'Y' ], [ 'B', 'Z' ] ]
Handling Edge Cases
It's important to handle empty arrays and invalid inputs:
const cartesianProductSafe = (arr1, arr2) => {
// Handle null, undefined, or empty arrays
if (!Array.isArray(arr1) || !Array.isArray(arr2)) return [];
if (arr1.length === 0 || arr2.length === 0) return [];
return arr1.flatMap(a => arr2.map(b => [a, b]));
};
console.log("Empty array:", cartesianProductSafe([], [1, 2]));
console.log("Normal case:", cartesianProductSafe([1], [2, 3]));
Empty array: [] Normal case: [ [ 1, 2 ], [ 1, 3 ] ]
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| Nested Loops | High | Fast | All browsers |
| flatMap/map | Very High | Moderate | ES2019+ |
Conclusion
The Cartesian product creates all possible ordered pairs from two sets. Use nested loops for maximum performance or flatMap() for cleaner, more functional code. Always handle edge cases like empty arrays.
