Cross Product of Arrays

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to create a new array out of the two supplied by generating every possible pair from the elements of the two arrays. We will use JavaScript's built-in methods such as reduce(), map(), and concat() to achieve this. By the end of this lab, you will have a good understanding of how to work with arrays in JavaScript.


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`") subgraph Lab Skills javascript/variables -.-> lab-28228{{"`Cross Product of Arrays`"}} javascript/data_types -.-> lab-28228{{"`Cross Product of Arrays`"}} javascript/arith_ops -.-> lab-28228{{"`Cross Product of Arrays`"}} javascript/comp_ops -.-> lab-28228{{"`Cross Product of Arrays`"}} javascript/higher_funcs -.-> lab-28228{{"`Cross Product of Arrays`"}} end

Creating an Array Cross Product in JavaScript

To create an array cross product in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.reduce(), Array.prototype.map(), and Array.prototype.concat() to produce every possible pair from the elements of the two arrays.
  3. The function xProd() takes in two arrays as arguments and creates a new array out of the two supplied by creating each possible pair from the arrays.
  4. Here's an example of the xProd() function in action:
const xProd = (a, b) =>
  a.reduce((acc, x) => acc.concat(b.map((y) => [x, y])), []);

xProd([1, 2], ["a", "b"]); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

This will return an array containing all possible pairs of elements from the two input arrays.

Summary

Congratulations! You have completed the Cross Product of Arrays lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like