Background: Users will fill out a google form and separate their answers with commas. I would like to write a script that can separate cells into rows for each comma used; however, I need to do this for multiple columns.
For example, here are screenshots of the concept that I would want:
How it starts
End goal
And here is my actual data set: My sheet
I have columns A through S. I only want to look at columns D through L and check if they have commas. In the picture, you can see that the first three rows of information do not contain commas. I would just like the code to return those values as they are. In row 5, column D through L does contain commas that represent separate responses, and so I would like those values to be split into separate rows in the output.
This is what I have so far, that I found the bulk of from someone else on Stackoverflow. This code works but only if you specify one column.
For example, on a blank google sheet I write =split_rows(Sheet1!A:S,3), which only checks column 3 of my other sheet for commas. I need a code that will do the same but for several columns and split up the values.
function split_rows(anArray, splitColumnIndex) {
var output = [];
for (i in anArray){ // for each row
var current_cell = anArray[i][splitColumnIndex]; // current cell in loop
if (current_cell.toString().indexOf(",")>-1) { // if the cell in the designated column contains a comma,
var splitArray = current_cell.split(","); // split values in specified column
for (j in splitArray){ // for each split cell value
var row = anArray[i].slice(0); // take a copy of source row
row[splitColumnIndex] = alltrim(splitArray[j]); // replace comma separated value with current split value
output.push(row); // push new row to output
}
}
else {
var row = anArray[i].slice(0);
output.push(row);
}
}
return output;
}
function alltrim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
Here is an example of my sheet; https://docs.google.com/spreadsheets/d/1mgqKriAxf6-hAPNJ9Um8i9SD22TxDXVKM8llRn0sCS4/edit#gid=0

