In JavaScript, generating combinations from arrays of varying sizes can be a complex task. Let's explore a solution using a recursive helper function.
The cartesian function takes an arbitrary number of arrays as parameters and returns an array of all possible combinations. It utilizes a recursive helper function, helper, which iterates through each element in an array and pushes it to a cloned version of the current combination. If the current array is not the last one, it recursively calls helper to generate all combinations for the remaining arrays.
The cartesian function can be used as follows:
cartesian([0,1], [0,1,2,3], [0,1,2]);
This will produce the desired combinations:
[0,0,0], [0,0,1], [0,0,2], [0,1,0], [0,1,1], [0,1,2], [0,2,0], [0,2,1], [0,2,2]
To use this solution with an array of arrays, simply pass the array as a single parameter to the cartesian function. The helper function will automatically iterate through the nested arrays to generate all possible combinations.
var data = [[0,1], [0,1,2,3], [0,1,2]]; var combinations = cartesian(data);
The above is the detailed content of How to Generate All Combinations from Multiple Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!