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

How Can I Calculate the Cartesian Product of Multiple Arrays in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 14:10:22144browse

How Can I Calculate the Cartesian Product of Multiple Arrays in JavaScript?

The Cartesian Product of Multiple Arrays in JavaScript

JavaScript provides a straightforward way to determine the Cartesian product of several arrays. The Cartesian product involves combining elements from each array to form a new array, resulting in every possible combination.

For instance, given the arrays [1, 2] and [10, 20], the Cartesian product would be [[1, 10], [1, 20], [2, 10], [2, 20]].

1-Line Solution with Modern JavaScript (ECMAScript 2020):

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

Deeper Dive into the Solution:

This solution employs two key JavaScript features:

  1. Spread Operator (...): This operator is used to spread the arrays into separate arguments, allowing them to be supplied to a function as parameters.
  2. Array.reduce(...): It is utilized to recursively combine the arrays, with each step performing the following:

    • Flattens the current result array using the flatMap() method.
    • Iterates over the next array.
    • Appends each element from the next array to the flattened result.
    • Flattens the result again.

Example:

let output = cartesian([1, 2], [10, 20], [100, 200, 300]);

This would produce:

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

JavaScript continues to evolve, and the new features introduced in ECMAScript 2020 enable us to write more concise and efficient code. This improved solution demonstrates the power of modern JavaScript for complex problems.

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

Statement:
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