-1

I'd like to parse a comma seperated string into an 2d-array. The values are seperated with a comma and each new line with a new line character.

$A$1,$B$1,$C$1,$D$1,$E$1,$F$1,$G$1 $A$2,"$B,$2",$C$2,$D$2,$E$2,$F$2,$G$2 $A$3,$B$3,,,,, $A$4,$B$hg4,$C$4,$D$4,$E$4,$F$4,$G$4 $A$5,$B$5,$C$5,$D$5,$E$5,$F$5,$G$5 $A$6,$B$6,$C$6,$D$6,$E$6,$F$6,$G$6 $A$7,$B$7,$C$7,,$E$7,$F$7,$G$7 $A$8,$B$8,$C$8,,$E$8,$F$8,$G$8 $A$9,$B$9,$C$9,,$E$9,$F$9,$G$9 $A$10,$B$10,$C$10,,$E$10,$F$10,$G$10 $A$11,$B$11,$C$11,,$E$11,$F$11,$G$11 $A$12,$B$12,$C$12,$D$12,$E$12,$F$12,$G$12 $A$13,,$C$13,$D$13,$E$13,$F$13,$G$13 ,,$C$14,$D$14,$E$14,$F$14,$G$14 ,,$C$15,$D$15,$E$15,$F$15,$G$15 $A$16,$B$16,$C$16,$D$16,$E$16,$F$16,$G$16 

The desired outcome should be like this:

arr = [[$A$1],[$B$1],[$C$1],[$D$1],[$E$1],[$F$1],[$G$1]],[[$A$2],["$B,$2"],[$C$2],[$D$2],[$E$2],[$F$2],[$G$2]],[[$A$3],[$B$3],[],[],[],[],[]],[[$A$4],[$B$4],[$C$4],[$D$4],[$E$4],[$F$4],[$G$4]],...
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
dummy
  • 21
  • 3
  • Sounds like an interesting problem. Can you give us some smaller, testable expected input to output? Would you mind explaining what you have tried and where you got stuck? – Mike Cluck Nov 15 '17 at 14:42
  • there's nothing in jQuery for this. – Alnitak Nov 15 '17 at 14:43
  • 1
    Stack Overflow is not a free code writing service, please show your code/effort and what the actual problem is. – Cerbrus Nov 15 '17 at 14:44
  • You don't need jquery for this, this is just a javascript thing. [Stack Overflow already has this answered](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – Jeff Nov 15 '17 at 14:50
  • 1
    Possible duplicate of [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – Jeff Nov 15 '17 at 14:51
  • @Jeff that doesn't work for CSV when you might have the breaking character appearing within a quoted string – Alnitak Nov 15 '17 at 14:52

1 Answers1

0

You could split by new line and then split with the preserving quote regex from this answer.

Later map items in an array. Voila!

var string = '$A$1,$B$1,$C$1,$D$1,$E$1,$F$1,$G$1\n$A$2,"$B,$2",$C$2,$D$2,$E$2,$F$2,$G$2\n$A$3,$B$3,,,,,\n$A$4,$B$4,$C$4,$D$4,$E$4,$F$4,$G$4',
    result = string.split('\n').map(s => s.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(s => [s]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392