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] }.
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;
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!