Calculating Cartesian Product with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28189{{"`Calculating Cartesian Product with JavaScript`"}} javascript/data_types -.-> lab-28189{{"`Calculating Cartesian Product with JavaScript`"}} javascript/arith_ops -.-> lab-28189{{"`Calculating Cartesian Product with JavaScript`"}} javascript/comp_ops -.-> lab-28189{{"`Calculating Cartesian Product with JavaScript`"}} javascript/higher_funcs -.-> lab-28189{{"`Calculating Cartesian Product with JavaScript`"}} javascript/spread_rest -.-> lab-28189{{"`Calculating Cartesian Product with JavaScript`"}} end

Cartesian Product

To calculate the cartesian product of two arrays, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.reduce(), Array.prototype.map(), and the spread operator (...) to generate all possible element pairs from the two arrays.
  3. 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.

Other JavaScript Tutorials you may like