0

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

TheMaster
  • 45,448
  • 6
  • 62
  • 85
onit
  • 2,275
  • 11
  • 25

2 Answers2

1

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])
  }
}
RemcoE33
  • 1,551
  • 1
  • 4
  • 11
0

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++);
  }
}
Cooper
  • 59,616
  • 6
  • 23
  • 54