Home > Mobile >  Combine ranges in one function
Combine ranges in one function

Time:05-20

I got a function to shuffle multiple columns with different amount of values. For every column I have a function that shuffles the values in that column. I Combine all those functions into one function that shuffles all the columns.

function shuffleLevel345() {
  shuffleColumnA();   
  shuffleColumnB();   
  shuffleColumnC();   
  shuffleColumnD();   
  shuffleColumnE();   
}
function shuffleColumnA() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('level_345');
  var range = sheet.getRange("A1:A101");
  range.setValues(shuffleArray(range.getValues()));    
}  
function shuffleColumnB() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('level_345');
  var range = sheet.getRange("B1:B99");
  range.setValues(shuffleArray(range.getValues()));    
}  
function shuffleColumnC() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('level_345');
  var range = sheet.getRange("C1:C89");
  range.setValues(shuffleArray(range.getValues()));    
}  
function shuffleColumnD() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('level_345');
  var range = sheet.getRange("D1:D124");
  range.setValues(shuffleArray(range.getValues()));    
}  
function shuffleColumnE() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('level_345');
  var range = sheet.getRange("E1:E75");
  range.setValues(shuffleArray(range.getValues()));    
}

Can I combine it to one function with all ranges?

I have tried it with:

    var ranges = sheet.getRangeList(['A1:A101','B1:B99','C1:C89','D1:D124','E1:E75']);

But that didn't work.

CodePudding user response:

Probably it can be done with a loop this way:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('level_345');
var ranges = ['A1:A101','B1:B99','C1:C89','D1:D124','E1:E75'];

ranges.forEach(r => shuffleRange(r, sheet));

function shuffleRange(r, sheet) {
  var range = sheet.getRange(r);
  range.setValues(shuffleArray(range.getValues()));
} 

Or this way:

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('level_345');
const ranges = ['A1:A101','B1:B99','C1:C89','D1:D124','E1:E75'];

for (let r of ranges) {
  let range = sheet.getRange(r);
  range.setValues(shuffleArray(range.getValues()));
}
  • Related