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
Selected Reading
Compute cartesian product of elements in an array in JavaScript
Cartesian Product
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.
For example − If the two arrays are −
const arr1 = [1, 2, 3]; const arr2 = [4, 5];
Then their cartesian product will be −
const product = [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]];
Example
The code for this will be −
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]].concat(arr2[j])
);
};
};
return res;
};
console.log(cartesianProduct(arr1, arr2));
Output
And the output in the console will be −
[ [ 1, 4 ], [ 1, 5 ], [ 2, 4 ], [ 2, 5 ], [ 3, 4 ], [ 3, 5 ] ]
Advertisements
