edinvnode
edinvnode

Reputation: 3537

JavaScript Transpose the Data

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"
"[email protected]","1 123 456","Some St. 1","700"
"[email protected]","1 123 789","Some St. 2","800"
"[email protected]","1 123 654","Some St. 3","900"
"[email protected]","1 123 987","Some St. 4","1000" ';

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

var string = '"EMAIL","[email protected]","[email protected]","[email protected]","[email protected]"
"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"';

Upvotes: 1

Views: 377

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138235

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");

Upvotes: 2

Related Questions