Home > OS >  How to repeat each value in a range n times in another range? (Google App Script)
How to repeat each value in a range n times in another range? (Google App Script)

Time:10-23

My Code:

function Repeatn() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet() ;

  var mycount = ss.getRange(1, 1).getValue() ;

   for (i=0; i!=7; i  ){
    var Pname = ss.getRange(i 5, 3).getValue() ;
    if (Pname ==""){
      break ;
    }
    else {
        for (var k=0; k!=mycount; k  ){
        ss.getRange(k 1, 6).setValue(Pname) ;
        }   
    
      }
  
      }

  }

[This is what I am trying to achieve]1 [My current Output]2

I cannot figure out how to paste each value from column C in column F one after the other. Need help.

CodePudding user response:

Use Array().filter(), Array().forEach() and Array().push(), like this:

/**
* Repeats each row in rangeToRepeat timesToRepeat times and
* puts the result in rangeToFill.
*/
function repeatRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const timesToRepeat = sheet.getRange('A1').getValue();
  const rangeToRepeat = sheet.getRange('C5:C');
  const rangeToFill = sheet.getRange('F1');
  const values = rangeToRepeat.getValues()
    .filter(String);
  const result = [];
  values.forEach(row => {
    let count = timesToRepeat;
    while (count) {
      result.push(row);
      count--;
    }
  });
  rangeToFill
    .offset(0, 0, result.length, result[0].length)
    .setValues(result);
}
  • Related