Duplicate rows in google spreadsheet based on value

I am trying to programmatically duplicate rows in a google spreadsheet. I would like the number of times a string is repeated based on one of the values ​​of the string itself.

For example, let's say I have a table like this:

enter image description here

You can see that there are numbers in column C. The value in column C is the number of times I would like to duplicate the row. This is what the desired output would look like:

enter image description here

Technically, if the value in column C is 3, we will duplicate the row twice.

Any ideas on how to script a google spreadsheet for this would be great!

Thank!

+3


source to share


1 answer


It's pretty simple and you had to try it yourself. I'm sure when you read the code below, you say, "Oh, of course, I could do this easily" ... right?



function autoDup() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var newData = [];
  for(var n in data){
    newData.push(data[n]);
    if(!Number(data[n][2])){continue};// if column 3 is not a number then do nothing
    for(var c=1 ; c < Number(data[n][2]) ; c++){ // start from 1 instead of 0 because we have already 1 copy
      newData.push(data[n]);//store values
    }
  }
  sheet.getRange(1,1,newData.length,newData[0].length).setValues(newData);// write new data to sheet, overwriting old data
}

      

+6


source







All Articles