Why does this reverse loop give me an error in Google Apps Script?

346 views Asked by At

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

2

There are 2 answers

0
RemcoE33 On BEST ANSWER

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:

function test(){
  const arr = [[1,2],[2,2],[3,2],[4,2]];
  
  console.log(arr.length) // Returns 4
 
  for (let i = arr.length; i >= 0; i--){
    console.log(arr[i][0])
  }
}

So add a -1 after the .length:

function test(){
  const arr = [[1,2],[2,2],[3,2],[4,2]];
  
  for (let i = arr.length - 1; i >= 0; i--){
    console.log(arr[i][0])
  }
}
0
Cooper On

You can also do it this way:

function formatBoqPipework() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName('BOQ Pipework');
  const rg = sh.getRange(5, 1, sh.getLastRow(), 14);
  const vs = rg.getValues();
  let d = 0;
  for (let i = 0; i < vs.length; i++) {
    if (vs[i][0] == 'Pipework' || vs[i][0] == '')sh.deleteRow(i + 5 - d++);
  }
}