Skip to content Skip to sidebar Skip to footer

Challenge Looping Through An Array To Delete Rows In Google Apps Script

The following function deletes rows in a Google sheet based on a specific value/item, I was hoping to modify this to take an array of items to delete. Original function //GLOBALS

Solution 1:

Issues:

  • If you have two nested for loops, make sure both counter variables are not the same (i).
  • j is used as an index of DELETE_VAL. This doesn't correspond to the sheets rows you want to delete (SHEET.deleteRow(j+1);). That should be i instead (SHEET.deleteRow(i+1);).
  • Also, instead of having an inner for loop, I'd suggest using includes in order to check whether the array DELETE_VAL includes the corresponding cell value. This way, there's no need to declare j, which has been the cause of this confusion.

Code snippet:

function deleteEachRow(sheetName){
  var SHEET = spreadSheet.getSheetByName(sheetName);
  var RANGE = SHEET.getDataRange();
  var rangeVals = RANGE.getValues();
  for(var i = rangeVals.length-1; i >= 0; i--){
    if (DELETE_VAL.includes(rangeVals[i][COL_TO_SEARCH])) {
      SHEET.deleteRow(i+1);
    };
  };
};

Post a Comment for "Challenge Looping Through An Array To Delete Rows In Google Apps Script"