- Related Questions & Answers
- Cartesian product of multiple arrays in JavaScript
- Compute cartesian product of elements in an array in JavaScript
- Dash separated cartesian product of any number of arrays in JavaScript
- Finding union of two sets in JavaScript
- Adding two Sets in Javascript
- Subtract two Sets in Javascript
- Product of two number using HOC - JavaScript
- Merge two sets in Java
- Get the intersection of two sets in Java
- Get the union of two sets in Java
- Maximum Product of Two Numbers in a List of Integers in JavaScript
- Get the asymmetric difference of two sets in Java
- Explain sets in JavaScript?
- Java Program to compare two sets
- How to get the product of two integers without using * JavaScript

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

Inset theory a Cartesian product is a mathematical operation that returns a set (or product set or simply product) from multiple sets.

That is, 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 are required to write a JavaScript function that takes in two arrays let us call them arr1 and arr2, they both represent two distinct sets.

The function should construct a 2-D array that contains the cartesian product of those two sets and finally return that array.

Following is the code −

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 res = []; for (let i = 0; i < arr1.length; i += 1) { for (let j = 0; j < arr2.length; j += 1) { res.push([arr1[i], arr2[j]]); }; }; return res; }; console.log(cartesianProduct(arr1, arr2));

Following is the output on console −

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

Advertisements