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
forloops, make sure both counter variables are not the same (i). jis used as an index ofDELETE_VAL. This doesn't correspond to the sheets rows you want to delete (SHEET.deleteRow(j+1);). That should beiinstead (SHEET.deleteRow(i+1);).- Also, instead of having an inner
forloop, I'd suggest using includes in order to check whether the arrayDELETE_VALincludes the corresponding cell value. This way, there's no need to declarej, 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"