You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 char1Values and only pairing with the same-index item in char2Values, we added a nested loop: for every item in char1Values, we iterate through every item in char2Values and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:52:12