1
votes

Currently I have a script below that duplicates rows but only keeps the first cell of the row's data. But currently when running it on my spreadsheet it creates 15 rows per current row - it's supposed to be creating 4 per current row :(

function duplicateRows() {

var sh, v, arr, c, b;

sh = SpreadsheetApp.getActive()
    .getSheetByName('products_export')
v = sh.getDataRange()
    .getValues();
arr = [v[0]];
v.splice(1)
    .forEach(function (r, i) {
        arr.push(r)
        c = 0
        while (c < 3) {
            arr.push([r[0],"","","","","","","","","","","","","","","","","","","","","",""])
            c += 1;
        }
    })
sh.getRange(1, 1, arr.length, arr[0].length)
    .setValues(arr);
}
1

1 Answers

0
votes

You probably just ran the function twice.

Initial:

N  NAME  AGE
1  fish  cat
2  fire  hat

First Execution:

N  NAME  AGE
1  fish  cat
1
1
1
2  fish  cat
2
2
2

*four of each:

1 * 4 = 4

4 - 1 (base row) = 3 copies

Second Execution:

N  NAME  AGE
1  fish  cat
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
2  fish  cat
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2

*four copies of each

4 * 4 = 16

16 - 1 (base row) = 15 copies