Finding All Combinations (Cartesian Product) of JavaScript Array Values
To determine all combinations of values in a set of JavaScript arrays, we employ recursion. Unlike permutations, this process seeks to combine elements across multiple arrays rather than rearrange elements within a single array.
Here's a recursive solution that generates the Cartesian product of the given arrays:
<code class="js">function allPossibleCases(arr) { if (arr.length === 0) { return []; } else if (arr.length === 1) { return arr[0]; } else { var result = []; var allCasesOfRest = allPossibleCases(arr.slice(1)); for (var i = 0; i < allCasesOfRest.length; i++) { for (var j = 0; j < arr[0].length; j++) { result.push(arr[0][j] + allCasesOfRest[i]); } } return result; } }</code>
For example, given the input arrays:
<code class="js">var first = ['a', 'b', 'c', 'd']; var second = ['e']; var third = ['f', 'g', 'h', 'i', 'j'];</code>
The allPossibleCases function would output the following combinations:
aef aeg aeh aei aej bef beg
... and so on, producing all possible combinations of elements from the three input arrays.
The above is the detailed content of How to Generate All Combinations of JavaScript Array Values Using Recursion?. For more information, please follow other related articles on the PHP Chinese website!