Reputation: 198
I have a google docs spreadsheet with rows like this:
| | things; separated;by;semicolons;with;line;breaks |
something | something else | A;B;C;D;E;F;G | one more thing
| | K;L;M;N;O;P;Q |
-----------------------------------------------------------------------------------------------
i want to split the third column by linebreaks, putting each in one copy of the entire line, overwriting the third cell and then split that cell by the semicolons. At the end, the previous row should be converted to something like this:
something|something else|things|separated|by|semicolons|with|line|breaks| one more thing
-----------------------------------------------------------------------------------------
something|something else| A | B | C| D | E | F | G | one more thing
-----------------------------------------------------------------------------------------
something|something else| K | L | M| N | O | P | Q | one more thing
-----------------------------------------------------------------------------------------
I tried this function, but some cells overlap and overwrite others:
function splitColumnAndRepeatRows(anArray, splitColumnIndex) {
var output = [];
for (i in anArray){ // for each row
var splitArray = anArray[i][splitColumnIndex].split(/\n/g); // split values by line breaks
for (j in splitArray){ // for each split array
var row = anArray[i].slice(0); // copies the entire line
row.splice(2,1,splitArray[j].split(";")); // inserts the splited values overwriting the third cell
output.push(row);
}
}
return output;
}
So the splice function doesn't insert the split values between cells 2 and 4. The split values are placed from the third cell on, overwriting the fourth cell ("one more thing", in the example), like this:
something|something else|things|separated|by|semicolons|with|line|breaks
------------------------------------------------------------------------
Can someone point out where is my mistake? I hope I explained it well enough.
Thanks in advance.
Upvotes: 0
Views: 1156
Reputation: 1142
There are two issues with your code. One is that you are replacing one cell every time you run the splice function. Since you do this many times, you overwrite that last "one more thing" cell as well. Instead, replace it once at the beginning only.
The other issue, though I'm not sure what you intended, is I don't think you want to supply an array to the splice function as this creates an inner array in your row array. Instead, loop over the array values and call splice with each one.
This inner loop code should fix your issue:
for (j in splitArray){ // for each split array
var row = anArray[i].slice(0); // copies the entire line
var split = splitArray[j].split(";");
var pos = 0;
row.splice(2,1); // deletes the third cell
for (var k in split) {
row.splice(2+pos,0,split[k]); // inserts the splited values starting at cell 2
pos++;
}
output.push(row);
}
Upvotes: 2