Home > Web Front-end > JS Tutorial > How to Efficiently Calculate the Cartesian Product of Multiple Arrays in JavaScript?

How to Efficiently Calculate the Cartesian Product of Multiple Arrays in JavaScript?

Mary-Kate Olsen
Release: 2024-12-31 05:55:18
Original
959 people have browsed it

How to Efficiently Calculate the Cartesian Product of Multiple Arrays in JavaScript?

Implementing the Cartesian Product of Multiple Arrays in JavaScript

The Cartesian product of multiple arrays comprises every possible combination of elements from the input arrays. This operation is essential for generating all possible combinations or permutations from a set of data.

The 1-Line Answer (ES2020)

const cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
Copy after login

Explanation

The Cartesian product is computed in the following manner:

  1. Reduce: Use this method to iterate over each array and combine them.
  2. flatMap: Flatten the reduced array by combining all possible combinations of elements from two input arrays.
  3. flat: Simplify the nested array by removing empty arrays or elements.

Example

To apply the Cartesian product on arrays with values, consider the following example:

const output = cartesian([1, 2], [10, 20], [100, 200, 300]);
Copy after login

The expected output is:

[
  [1, 10, 100],
  [1, 10, 200],
  [1, 10, 300],
  [1, 20, 100],
  [1, 20, 200],
  [1, 20, 300],
  [2, 10, 100],
  [2, 10, 200],
  [2, 10, 300],
  [2, 20, 100],
  [2, 20, 200],
  [2, 20, 300],
]
Copy after login

This demonstrates the calculation of all possible combinations of elements from the given arrays, resulting in a complete Cartesian product.

The above is the detailed content of How to Efficiently Calculate the Cartesian Product of Multiple Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template