如何用循环实现JavaScript不等长二维数组的逐行取数全组合
Absolutely, you can absolutely achieve this in JavaScript—this problem is essentially calculating the Cartesian product of the arrays in your 2D list. There are multiple ways to implement it, including using loops (both iterative and recursive) and functional-style approaches. Let’s break down a few solutions:
1. Iterative Loop Approach (Directly Using Loops)
This method builds combinations step-by-step with nested loops, which directly addresses your question about using loops. Here’s how it works:
function getCartesianProduct(arrays) { // Start with an empty combination as the base case let result = [[]]; for (let i = 0; i < arrays.length; i++) { const currentRow = arrays[i]; const tempCombos = []; // Pair every existing combination with each element in the current row for (const existingCombo of result) { for (const item of currentRow) { tempCombos.push([...existingCombo, item]); } } result = tempCombos; } return result; } // Example usage matching your input const a = [1, 2, 3]; const b = ["orange", "poke"]; const c = ["melon", "table", 93, 71, "rock"]; const arrayA = [a, b, c]; const allCombinations = getCartesianProduct(arrayA); // Iterate through each combination to run your custom operation allCombinations.forEach(combo => { console.log("Processing combination:", combo); // Insert your operation here (e.g., transform, validate, log) });
How it works:
- We start with
[[]]—this represents the empty starting point before processing any rows. - For each row in your 2D array, we take every existing combination and append each element from the current row to it, creating new valid combinations.
- After processing all rows,
resultcontains every possible combination of one element from each row.
2. Recursive Approach (Alternative to Explicit Loops)
If you prefer a more elegant, recursive solution (which still uses loops under the hood but in a structured way), here’s an option:
function getCartesianProductRecursive(arrays) { // Base case: no rows left to process, return empty combination if (arrays.length === 0) return [[]]; const firstRow = arrays[0]; const remainingRows = arrays.slice(1); // Recursively get combinations for the rest of the rows const restCombinations = getCartesianProductRecursive(remainingRows); // Pair each element in the first row with every combination from the rest return firstRow.flatMap(item => restCombinations.map(combo => [item, ...combo])); } // Usage is identical to the iterative method const recursiveCombinations = getCartesianProductRecursive(arrayA); recursiveCombinations.forEach(combo => { console.log("Processing recursive combination:", combo); });
How it works:
- The recursion breaks the problem into smaller chunks: take the first row, get all combinations of the remaining rows, then combine each element of the first row with those combinations.
flatMapsimplifies flattening the nested array of combinations into a single list.
3. Functional Style with Array.reduce()
For a concise, functional approach, you can use reduce to build combinations iteratively:
const getCartesianProductReduce = (arrays) => arrays.reduce((acc, currentRow) => acc.flatMap(combo => currentRow.map(item => [...combo, item])), [[]]); // Usage const reduceCombinations = getCartesianProductReduce(arrayA); reduceCombinations.forEach(combo => { console.log("Processing reduce combination:", combo); });
How it works:
reducestarts with the initial value[[]](empty combination).- For each row,
flatMapandmapwork together to append each element of the current row to every existing combination, mirroring the iterative loop logic in a more compact form.
All these methods will generate exactly the combinations you described—each combination is an array with one element from each row of your 2D array. You can then loop through the resulting list to run your custom operation on every combination.
内容的提问来源于stack exchange,提问作者A_Leaf_Wolf

