0

I have this below response

Response

const result = [
  {
    Id: "1",
    Char1: "a; b; c",
    Char2: "d; e; f"
  }
];

Currently I am generating output like below from my below JS code

Id,Char1,Char2
1,a,d
1,b,e
1,c,f

But I want to generate output like below with all combination of Char1 and Char2 with rest of the data-

Id,Char1,Char2
1,a,d
1,a,e
1,a,f
1,b,d
1,b,e
1,c,f
1,c,d
1,c,e
1,c,f

JS -

result
    .reduce((acc, {
        Id,
        Char1,
        Char2
    }) => {
        const a = Char1.split(";");
        const c = Char2.split(";");
        a.forEach((item, index) => {
            acc.push({
                Id: Id,
                Char1: item,
                Char2: c[index]
            });
        });
        return acc;
    }, [])
    .forEach(item => {
        lines.push(rowData.map(key => item[key]).join(","));
    });
dh4ze
  • 449
  • 1
  • 5
  • 10
learningmode
  • 137
  • 1
  • 10

3 Answers3

1

For every item in Char1's split array, you need to loop over every item in Char2's split array. So, you can use an inner .forEach loop within your a.forEach to loop over Char2's values like so:

const result = [{
  Id: "1",
  Char1: "a; b; c",
  Char2: "d; e; f"
}];

const combs = result.reduce((acc, {Id, Char1, Char2}) => {
  const a = Char1.split(";");
  const c = Char2.split(";");
  a.forEach((aitem) => {
    c.forEach((citem) => {
      acc.push({Id, char1: aitem.trim(), char2: citem.trim()});
    })
  });
  return acc;
}, [])

const ppres = Object.keys(result[0]) + combs.reduce((a, o) => a +Object.values(o) +'\n', '\n');
console.log(ppres);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Try using two forEach

result
    .reduce((acc, {
        Id,
        Char1,
        Char2
    }) => {
        const a = Char1.split(";");
        const c = Char2.split(";");
        a.forEach((item, index) => {

          c.forEach((item1,index1)=>{
              acc.push({
                Id: Id,
                Char1: item,
                Char2: item1
            });

          })

        });
        return acc;
    }, [])
    .forEach(item => {
        lines.push(rowData.map(key => item[key]).join(","));

    });
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
0

// Getting this from your api response you can do
const Id = "1";
const Char1 = ["a", "b", "c"];
const Char2 = ["d", "e", "f"];

const combo = [];  // To hold the final array

Char1.forEach(function(a1){
  Char2.forEach(function(a2){
    combo.push(`${Id}, ${a1}, ${a2}`);  // Two loops to get all combinations, put same id in every string.
  });
});

console.log(combo);
Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48