Cartesian Product: Generating Combinations of Array Values in JavaScript
Problem Description:
Given an arbitrary number of JavaScript arrays, how do we compute the Cartesian product of their elements, effectively generating all possible combinations of their values?
Solution:
While this problem may resemble permutation, it is a classic task involving the Cartesian product. Using recursion, we can implement an algorithm to achieve this:
Define an input list of arrays:
<code class="js">var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']];</code>
Create a recursive allPossibleCases function:
<code class="js">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 i = 0; i < arr[0].length; i++) { for (var j = 0; j < allCasesOfRest.length; j++) { result.push(arr[0][i] + allCasesOfRest[j]); } } return result; } }</code>
Instantiate the allPossibleCases function with the input list of arrays and print the results:
console.log(allPossibleCases(allArrays));
Output:
This code will output all possible combinations of the values in the input arrays, in the following format:
["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]
This algorithm efficiently generates the Cartesian product of the supplied arrays, providing a solution to the problem of creating exhaustive combinations of their elements.
The above is the detailed content of How to Generate All Possible Combinations of Array Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!