google sheets transpose new line to table
Code to Transpose New Line to Table in Google Sheets
function transposeNewLineToTable(inputString) {
var dataArray = inputString.split('\n').map(row => row.split('\t'));
var numRows = dataArray.length;
var numCols = dataArray[0].length;
var outputArray = [];
for (var j = 0; j < numCols; j++) {
var tempArray = [];
for (var i = 0; i < numRows; i++) {
tempArray.push(dataArray[i][j]);
}
outputArray.push(tempArray);
}
var outputString = outputArray.map(row => row.join('\t')).join('\n');
return outputString;
}
Explanation:
- Function Definition:
The
transposeNewLineToTable
function takes an input string as a parameter.Splitting the Input String:
The input string is split into an array of rows using the
split('\n')
method, and then each row is split into an array of cells using themap
function andsplit('\t')
.Determining Number of Rows and Columns:
The number of rows and columns in the data array is calculated using the
length
property.Transposing the Data:
Two nested loops are used to iterate through the rows and columns of the data array and construct a new transposed array called
outputArray
.Joining the Transposed Array:
The transposed array is then converted back to a string format by mapping each row to a string with cells joined by tabs, and then joining the rows with new line characters.
Returning the Transposed String:
- The transposed string is returned as the output of the function.