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())));
Explanation
The Cartesian product is computed in the following manner:
Example
To apply the Cartesian product on arrays with values, consider the following example:
const output = cartesian([1, 2], [10, 20], [100, 200, 300]);
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], ]
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!