如何用JavaScript生成JSON响应中数组的全笛卡尔积组合?
Generate All Possible Combinations Between Char1 and Char2
Got it, let's tweak your code to generate every possible combination of Char1 and Char2 values instead of just matching them by their index positions. Here's the adjusted version:
const result = [ { Id: "1", Char1: "a; b; c", Char2: "d; e; f" } ]; const lines = []; const rowData = ["Id", "Char1", "Char2"]; // Assuming this is your target field array const allCombinations = result.reduce((acc, { Id, Char1, Char2 }) => { const char1Values = Char1.split("; "); const char2Values = Char2.split("; "); // Use nested loops to create every possible pair char1Values.forEach(char1Item => { char2Values.forEach(char2Item => { acc.push({ Id: Id, Char1: char1Item, Char2: char2Item }); }); }); return acc; }, []); // Generate CSV lines as you originally did allCombinations.forEach(item => { lines.push(rowData.map(key => item[key]).join(",")); }); // Example output of lines: // ["1,a,d", "1,a,e", "1,a,f", "1,b,d", "1,b,e", "1,b,f", "1,c,d", "1,c,e", "1,c,f"]
What changed?
- Instead of looping through
char1Valuesand only pairing with the same-index item inchar2Values, we added a nested loop: for every item inchar1Values, we iterate through every item inchar2Valuesand push that pair into the accumulator array. - This ensures we get every possible combination, not just the index-matched ones.
If you have multiple objects in the result array, this code will handle that too—each object's Char1 and Char2 values will generate their own full set of combinations, all collected into the allCombinations array.
内容的提问来源于stack exchange,提问作者learningmode
相关产品推荐
相关产品推荐

