Cartesian Product of JavaScript Array Values
Problem:
Given an arbitrary number of JavaScript arrays of varying lengths, determine all combinations (Cartesian product) of their values.
Solution:
This task can be efficiently solved using recursion. It involves iterating through each array and combining its values with all possible combinations of the remaining arrays.
Consider the following implementation:
function allPossibleCases(arr) { if (arr.length === 1) { return arr[0]; } else { const result = []; const casesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of arr casesOfRest.forEach((c) => { for (let i = 0; i < arr[0].length; i++) { result.push(arr[0][i] + c); } }); return result; } }
Usage:
var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']]; var results = allPossibleCases(allArrays); // outputs ["acd", "bcd", "azd", ...]
Explanation:
The above is the detailed content of How to Generate All Combinations (Cartesian Product) of Values in JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!