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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 11:28:10122browse

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

Cartesian Product of Multiple Arrays in JavaScript

Introducing the Cartesian Product

In mathematics, the Cartesian product of multiple sets is the set of all possible ordered combinations of elements from those sets. For instance, the Cartesian product of sets [1, 2] and [10, 20, 300] is { [1, 10], [1, 20], [1, 300], [2, 10], [2, 20], [2, 300] }.

Implementation in JavaScript

1-Line JavaScript Solution (2020 Update)

Leveraging the power of modern JavaScript features, here's an ultra-concise solution spanning just a single line:

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

2-Line Vanilla JavaScript Solution

Prior to the 2020 updates, this was the shortest vanilla JavaScript solution:

let f = (a, b) => [].concat(...a.map(a => b.map(b => [].concat(a, b))));
let cartesian = (a, b, ...c) => b ? cartesian(f(a, b), ...c) : a;

Example Usage

Consider the input arrays:

input = [1, 2], [10, 20], [100, 200, 300]

To compute the Cartesian product, we can invoke the cartesian function:

const output = cartesian(...input);

The output variable would contain the expected Cartesian product:

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

The above is the detailed content of How to 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