- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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 Questions & Answers
- Cartesian product of multiple arrays in JavaScript
- Cartesian product of two sets in JavaScript
- Dash separated cartesian product of any number of arrays in JavaScript
- Finding the product of array elements with reduce() in JavaScript
- Product of non-repeating (distinct) elements in an Array in C++
- Product of all other numbers an array in JavaScript
- Finding product of an array using recursion in JavaScript
- Rearranging elements of an array in JavaScript
- Compute the sum of elements of an array which can be null or undefined JavaScript
- Difference between sum and product of an array in JavaScript
- Sum of distinct elements of an array in JavaScript
- Explain cartesian product in relational algebra (DBMS)?
- Rearrange an array to minimize sum of product of consecutive pair elements in C++
- Given an array of integers, find the pair of adjacent elements that has the largest product and return that product JavaScript
- Sum of distinct elements of an array - JavaScript

Advertisements