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]].
const cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
This solution employs two key JavaScript features:
Array.reduce(...): It is utilized to recursively combine the arrays, with each step performing the following:
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!