Introduction
In this lab, we will explore the concept of Cartesian Product and how to calculate it using JavaScript. We will learn how to use the Array.prototype.reduce(), Array.prototype.map() and the spread operator (...) to generate all possible element pairs from two arrays. By the end of the lab, you will have a better understanding of how to use these methods to calculate the Cartesian Product of two arrays.
Cartesian Product
To calculate the cartesian product of two arrays, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.reduce(),Array.prototype.map(), and the spread operator (...) to generate all possible element pairs from the two arrays. - Use the following code:
const cartesianProduct = (a, b) =>
a.reduce((p, x) => [...p, ...b.map((y) => [x, y])], []);
Example:
cartesianProduct(["x", "y"], [1, 2]);
// [['x', 1], ['x', 2], ['y', 1], ['y', 2]]
This will generate all possible combinations of elements from the two arrays.
Summary
Congratulations! You have completed the Cartesian Product lab. You can practice more labs in LabEx to improve your skills.