title: For loop runs again after condition is met
body: <p>I'm working on crating a function that adds data from numerous sheets in a Google Sheets document. The function creates production sheets that has a name and data slot as well as column titles for data that the function will paste into the sheet "Print". I am having an issue where a for loop seems to run an additional time even though the conditions are met as far as I can tell. Here is the code I have so far, its ugly but I'm just building this for myself. </p>
  
  <pre><code>function pasteToPrint(){
  
    var ui = SpreadsheetApp.getUi()
  
    var spreadsheet = SpreadsheetApp.getActive();
  
    var sheetName;
  
    var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  
    var lastCol;
  
    var lastRow;
  
    var a;
  
    var x;
  
    var y;
  
    var z;
  
    var array1 = [];
  
    var array2 = [];
  
    function getNextPage(){ // spreads subsequent data set to page break for printing 
      x = spreadsheet.getSheetByName("Print").getLastRow();
      y = x/32;
      y = Math.ceil(y);
      z = 32*y;
      return z;
    }
  
    for(var i = sheets.length-1; i &gt; 4; i--){ // loops through the appropriate sheets and pushes to array1
      lastCol = spreadsheet.getSheetByName(sheets[i].getName()).getLastColumn()+1;
      lastRow = spreadsheet.getSheetByName(sheets[i].getName()).getLastRow()+1;
      array1.push(spreadsheet.getSheetByName(sheets[i].getName()).getRange(1, 1, lastRow, lastCol).getValues());
    }
  
    for(var i = 0; i &lt; array1.length; i++){ 
      for(var j = 0; j &lt; array1[i].length; j++){
        // Looking for data that has a value grater than 0 at .slice(2,3)
        if(array1[i][j].slice(2,3) &gt; 0){ // Ref1
          for(var k = 0; k &lt; array1[i].length; k++){ // here I push that data to array2
            if(array1[i][k].slice(2,3) &gt; 0){ // ref 2
              array2.push(array1[i][k]);
            }
          }
          ui.alert(array2+" test 1"); // lets me know the content of array2
          ui.alert(array2.length); // tells me the length just to be sure
          for(var l = 0; l &lt; array2.length; l++){ // decides where to paste the next data set
            if(spreadsheet.getSheetByName("Print").getLastRow()&gt;1){ // ref 3
              a = getNextPage(); // returns the next 32nd line
            }
            else {
              a = 1; // starts at row 1
            } 
            // this next section is column formatting for the beginning of the production sheet
            // ref 4
            spreadsheet.getSheetByName("Print").getRange(a,1).setValue("Name:");    
            spreadsheet.getSheetByName("Print").getRange(a,3).setValue("Date:");
            a++; // moves to the next row
            spreadsheet.getSheetByName("Print").getRange(a,1).setValue("Product");
            spreadsheet.getSheetByName("Print").getRange(a,2).setValue("Work Order");
            spreadsheet.getSheetByName("Print").getRange(a,3).setValue("Planned Production");
            spreadsheet.getSheetByName("Print").getRange(a,4).setValue("Product Produced");
            spreadsheet.getSheetByName("Print").getRange(a,5).setValue("Steel Shortage");
            spreadsheet.getSheetByName("Print").getRange(a,6).setValue("Notes");
            a++ // moves to the next row
            // ref 5
            for(var m = 0; m &lt; array2[l].length-1; m++){ // HERE IS THE PROBLEM LOOP
              ui.alert(array2[m]+" test 2"); // I see this run an additional time after m = length
              spreadsheet.getSheetByName("Print").getRange(a,1).setValue(array2[m][0]);
              spreadsheet.getSheetByName("Print").getRange(a,2).setValue(array2[m][4]);
              spreadsheet.getSheetByName("Print").getRange(a,3).setValue(array2[m][2]);
              a++; 
            }
          }
          array2 = []; // array2 is emptied 
          break; // First if statement checking .slice(2,3) now has the function go to the next sheet
        }
      }
    }
  
    ui.alert("Function ended"); // just letting me know
  
  };
  
  </code></pre>
  
  <p>imagine that there are numerous sheets in this document with data like the following except that there might be hundreds of rows after the column titles with different part numbers and so on</p>
  
  <pre><code>Material  Req Planned Quantity MTs Planned Order
  AI UPC300 1   1                86  12744851
  </code></pre>
  
  <p>The Plan Quantity column is what the .slice(2,3) is looking for. By default when I paste the original data into the sheets from my inventory system the value of Planned Quantity will be 0. After I have gone through the document and planed production, this means I have assigned a value to planned quantity greater than 0, I will run the function to paste the data to the print sheet. There could be hundred of items but I will only plan a portion of them, that's why this is handy. I can't share the full document I'm working with because it has sensitive data in it. If you create a google sheet with one sheet named print and a second sheet named whatever you want you can then paste the example data on rows 1 and 2 of the second sheet and you will see the error I get which is     </p>
  
  <blockquote>
    <p>TypeError: Cannot read property '0' of undefined (line 138, file "arrayTest")</p>
  </blockquote>
  
  <p>You must also change <code>for(var i = sheets.length-1; i &gt; 4; i--)</code> to <code>for(var i = sheets.length-1; i &gt; 1; i--)</code>, change the 4 to a 1. I have more code in my document but it is comprised of separate functions from this function.</p>
  
  <p>I have added an image below that showcases how this would look before I utilize the function as well as how the Print sheet would look after the function has run. I had to screenshot this unfortunately so the data is condensed. Imagine that each section of data you see, green, blue, and white, are on their own sheets. For clarity the data in green would be contained in TestSheet1, the data in blue in TestSheet2, and the Print sheet would be totally blank before this function runs. Once I have entered my planned quantities in the Planned Quantity columns of TestSheet 1 and 2 I would then run the function. This would result in the data being pasted to the print page. I have added "ref" comments to the code to show where each step of the following explanation occurs. The function runs in this order: 1) The function will determine if a sheet has any values greater than zero in the Planned Quantity column, "ref 1". 2) The function would them loop through the sheet and push any row that met this criteria to array2, "ref 2". 3) The function will determine where to paste the data into the Print sheet based on data that may already by pated to the sheet, row 1, row 32, row 64, and so on, "ref 3". 4) the function will paste a header above the soon to be pasted data. This header include name, date, and column titles. 5) Once the header is placed the function will loop through array2 and paste is contents to the Print sheet, "ref 5". 6) the function will set array2 so that <code>array2 = []</code> and will then repeat the process for the next sheet until all the sheets have been gone over and there is no more data to paste into Print, "ref 6". </p>
  
  <p><a href="https://i.stack.imgur.com/yOi33.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yOi33.png" alt="Image of spreadsheets: &quot;Print&quot; only image of tab, &quot;TestSheet1&quot; cells in green, &quot;TestSheet2&quot; cells in blue, an example of the Print sheet after the function correctly runs"></a></p>