1

I am doing some work with data and I need a function that will transpose after data manipulation is finished. Right now the data looks like this.

var string ='"EMAIL","PHONE","ADDRESS","AREA"
"something@gmail.com","1 123 456","Some St. 1","700"
"something1@gmail.com","1 123 789","Some St. 2","800"
"something2@gmail.com","1 123 654","Some St. 3","900"
"something3@gmail.com","1 123 987","Some St. 4","1000" ';

I need a function that will convert these data into this:

var string = '"EMAIL","something@gmail.com","something1@gmail.com","something2@gmail.com","something3@gmail.com"
"PHONE","1 123 456","1 123 789","1 123 654","1 123 987"
"ADDRESS","Some St. 1","Some St. 2","Some St. 3","Some St. 4"
"AREA","700","800","900","1000"';
edinvnode
  • 3,497
  • 7
  • 30
  • 53
  • 1
    So you have that data as a string? – Jonas Wilms Jul 06 '19 at 17:23
  • 2
    And what have you tried to solve that problem? What was your particular problem in getting that desired result? You need to show some [mvce] of what you have tried. – t.niese Jul 06 '19 at 17:24
  • 1
    Related: https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript – MTCoster Jul 06 '19 at 17:26
  • 1
    This isn't a complete answer, rather a hint as to how I'd go about this: each line of your input is *almost* a [JSON array](https://www.json.org/), just without the `[` and `]` characters at either end. [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) will take care of the edge cases (like commas inside strings) for you. Then it's just a matter of [transposing the resulting array of arrays](https://stackoverflow.com/q/17428587/1813169). – MTCoster Jul 06 '19 at 17:30
  • 1
    `var arr = JSON.parse("[["+str.replace(/\n/g,"],[")+"]]");` – mplungjan Jul 06 '19 at 17:49
  • 2
    @mplungjan "parse csv in js" yields a lot of results, most of them use some very complicated regexes / replacers. Your solution is quite elegant IMO ... – Jonas Wilms Jul 06 '19 at 17:51
  • 1
    @JonasWilms yeah, I wanted to post a map/reduce but could not figure out an elegant enough map ;) – mplungjan Jul 06 '19 at 17:55

1 Answers1

2

Turn that data as a string into a 2D array (or table, matrix, ...), then you can transpose the matrix and join it back to a string:

 const transpose = array => array[0].map((col, i) => array.map(row => row[i]));

  const result = transpose(
    data.split("\n").map(row => row.split(","))
  ).map(row => row.join(",")).join("\n");
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151