This reverse loop is giving me the error TypeError: Cannot read property '0' of undefined and I can't find out why.
Here's the code part:
function formatBoqPipework() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const boqPipeworkSheet = ss.getSheetByName('BOQ Pipework');
const boqPipeworkRng = boqPipeworkSheet.getRange(5, 1, boqPipeworkSheet.getLastRow(), 14);
const boqPipeworkValues = boqPipeworkRng.getValues();
let lastRow = boqPipeworkSheet.getLastRow();
for (let a = boqPipeworkValues.length; a >= 0; a--) {
Logger.log(a)
if (boqPipeworkValues[a][0] == 'Pipework' || boqPipeworkValues[a][0] == '') {
//let row = a + 5
boqPipeworkSheet.deleteRow(a+5);
}
}
}
Appreciate any help.
Regards, Antonio
Arrays are 0 based and the .length will give you the "human" length. So in the example below (what will error out) you assign 4 to i and arr[4] does not exist. Because the array number is max 3 if you count from 0.
Error:
So add a -1 after the .length: