- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 ] ]

- Related Articles
- Cartesian product of multiple arrays in JavaScript
- Cartesian product of two sets in JavaScript
- Finding the product of array elements with reduce() in JavaScript
- Dash separated cartesian product of any number of arrays in JavaScript
- Compute the sum of elements of an array which can be null or undefined JavaScript
- Product of non-repeating (distinct) elements in an Array in C++
- Rearranging elements of an array in JavaScript
- Product of all other numbers an array in JavaScript
- Finding product of an array using recursion in JavaScript
- Difference between sum and product of an array in JavaScript
- Sum of distinct elements of an array in JavaScript
- Compute the differences between consecutive elements and append an array of numbers in Numpy
- Compute the median of the masked array elements in Numpy
- Compute the Hyperbolic tangent of the array elements in Python
- Compute the Hyperbolic sine of the array elements in Python

Advertisements