0

I have the following string:

"Vortioxetine[1], Imipramine[2], Citalopramasdddd[2], Vortioxetine[1], Imipramine[2], Citalopram[2]"

and I want to split it into an array with every other comma, so the result would be an array of

[0]Vortioxetine[1], Imipramine[2],
[1]Citalopramasdddd[2], Vortioxetine[1],
[2]Imipramine[2], Citalopram[2]

I currently have this code to split it by a single comma:

            const pharma = "Vortioxetine[1], Imipramine[2], Citalopramasdddd[2], Vortioxetine[1], Imipramine[2], Citalopram[2]"
            const split = pharma.split(',');
            for(const index in split){ 
                drawText(page, split[index], {
                    ...tableTextBodyCol3 , 
                    x: col6X + 2,
                });
            }

You can ignore the drawText area as that is program specific, but I would like it to draw 2 words on the page that I have where as right now it is just doing 1, let me know if other info is needed.

guitarman
  • 165
  • 7
  • Try to use `lodash` `chunk` to group splitted strings by 2 strings – Anatoly Jan 20 '22 at 17:12
  • See [this answer](https://stackoverflow.com/a/37826698/6243352) or try something like `const arr = s.split(/, */); const res = arr.map((e, i) => [e, arr[i+1]]).filter((e, i) => i % 2 === 0);` assuming your array is always even length. – ggorlen Jan 20 '22 at 17:17
  • Does this answer your question? [Split array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks) – ggorlen Jan 20 '22 at 17:17
  • @Anatoly No this produces a 2d array instead of a grouped 1D array. I tried to flatten the 2d array the chunk produced however it flattened it completely back into the original string. – guitarman Jan 20 '22 at 17:42
  • @guitarman You could easily `map` every 2-element inner array into a single string using `twoElementArray.join(', ')`, assuming that the spacing around the commas does not matter. – Jeff Bowman Jan 20 '22 at 18:07
  • @JeffBowman that's what I tried to hint – Anatoly Jan 20 '22 at 19:21

0 Answers0