Home > Article > Web Front-end > How to Generate All Possible Combinations of Values in JavaScript Arrays?
Finding Combinations of JavaScript Array Values
A challenge often encountered in JavaScript is finding all possible combinations of values across multiple arrays of varying lengths. This is distinct from permutations, where the order of elements matters.
To solve this problem, we employ a recursive approach:
<code class="javascript">function allPossibleCases(arr) { if (arr.length === 1) { return arr[0]; } else { var result = []; var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array for (var c in allCasesOfRest) { for (var i = 0; i < arr[0].length; i++) { result.push(arr[0][i] + allCasesOfRest[c]); } } return result; } }</code>
Consider an example with three arrays:
<code class="javascript">var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']];</code>
Calling allPossibleCases(allArrays) will output:
["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]
This method effectively combines all elements from the input arrays to generate all possible combinations, fulfilling the requirement posed in the original query.
The above is the detailed content of How to Generate All Possible Combinations of Values in JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!