What is the optimal way to update an array within a loop only when a certain condition is met?

I am currently working on a function that will iterate through folders in Google Drive, searching for files (Google Sheets) that match a specific date specified in a table cell. Once a matching file is found, the name of the containing folder is stored in the folderItems[0] and the file's URL is stored in folderItems[1]. The process continues until all matching files within a folder have been identified, after which it moves on to the next folder. These folderItem arrays are then collected in a parent array called "folderItemsContainer," creating a 2-dimensional array that can be easily outputted to a spreadsheet using .setValues().

My main challenge right now is determining the best placement for an increment variable. I need it to only increment when a filename match is found, without causing the loop to stop if no match is detected.

I have experimented with different structures, including switching between for and while loops and adding if statements at strategic points. I've also researched various answers on Stackoverflow, but none seem to directly apply to my situation. As someone who is relatively new to programming, I have tried multiple variations of code, but here is where I stand currently:

 // Your function code goes here...

Despite my efforts, the script seems to get stuck in an endless loop and never completes. My goal is to populate the folderItemsContainer array with arrays containing the necessary file information (parent folder name [0] and file URL [1]) for files that match the currentYearPeriod variable. Although I have made progress in refactoring the code, I have yet to find a solution to this issue.

Answer №1

It's important to understand the difference between each type of loop in programming. If you need to execute a set of instructions until a certain condition is met, like

file.getName().indexOf(currentYearPeriod) !== -1
, then a while loop would be more suitable than a for loop. The issue with your code is that the condition in the for loop is never met because the variable file doesn't change within the loop, leading to an infinite loop. Here is a suggested solution:

// declare a new variable
var cnt = 0;

while (StaffFolders.hasNext()) {
    currentFolder = StaffFolders.next();
    FolderFiles = currentFolder.getFiles();

    if (FolderFiles !== null) {
      while (FolderFiles.hasNext()) {
        file = FolderFiles.next();

        folderItems[cnt] = [];
        folderItems[cnt][0] = currentFolder.getName();
        folderItems[cnt][1] = file.getUrl();
        folderItemsContainer[cnt] = folderItems[cnt];

        cnt++;
      }
    }
    cnt = 0;
  }

Differences between loops:

for loops

For loops are used when the number of iterations is known beforehand. For example, printing each character of a string in the console:

const str = "hello";
for(let i = 0; i < str.length; i++) {
   console.log(str.charAt(i));
}
  • let i = 0 initializes the loop
  • i < str.length defines the end condition
  • i++ specifies how to iterate through the loop

while loops

While loops are ideal when the number of iterations is uncertain. For instance, searching for the index of a specific character in a string:

function getFirstL(str)
   let i = 0;
   while(i < str.length && str.charAt(i) !== "l"){
      i++;
   }
}

Answer №2

Understanding the concept of a for loop is crucial in programming.

for (initialization; condition; increment/decrement) {
  // code to be iterated
}

The initialization statement runs once before entering the loop.

The condition decides whether to execute the loop or not.

The increment/decrement statement runs after each iteration of the loop.

Your current for loop lacks an exit condition, such as a minimum or maximum value check like:

i < file.getName().indexOf(currentYearPeriod);

This means the loop will iterate from 0 up to that specified value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The attempt to access 'reading params' is resulting in an error due to undefined properties

Looking for some assistance in resolving an error I'm encountering. Below is a snippet of my code: const ProductScreen = ({match, history}) => { const [qty, setQty] = useState(1); const dispatch = useDispatch(); const productDetail ...

Storing Data Efficiently in AngularJS and NodeJS: Choosing Between Saving to a JSON File or a Database

I am a beginner in AngularJS and nodeJS, struggling to find the information I need. I am working on a small app as a training exercise - a personal lexicon where users can store and refer back to information they want to keep handy. My challenge lies in t ...

The issue arises when trying to use jQuery on multiple elements with the same class

Recently, I came across a jQuery script for my mobile menu that changes the class on click event. jQuery("#slide-out-open").click(function() { if( jQuery( this ).hasClass( "slide-out-open" ) ) { jQuery('#wrapper').css({overflow:"hidd ...

AngularJS POST request not functioning as expected

Seeking guidance in my AngularJS journey as a newcomer. I'm facing an issue where the call to the REST service is not reaching it despite including everything from controller and service to the actual service call. Here's a snippet of my code: ...

Why won't the button's color change when I try clicking on it?

I am currently learning vue and facing some challenges. The code I have is supposed to change the button color when clicked, but it's not working as expected. Any advice on how to fix this issue would be greatly appreciated. Thank you! let app = ...

AngularJS Jasmine test failure: Module instantiation failed

Everything was running smoothly with my angular app and tests using karma and jasmine. However, after adding a dependency in ui.bootstrap, my app continues to function as expected but now my tests won't run. Here is what I have: app.js - added depend ...

What is the best way to use a computed property as a style value for a component in Vue.js?

My component's template includes the following HTML element: .grid-item(:style="{ width: columnWidth, backgroundColor: 'blue' }") I want to dynamically set the width of this element using a computed property: computed: { columnWidth () ...

What is the trick to getting an accordion to expand when hovering, rather than when clicking?

Can the accordion be set to expand when hovering instead of clicking? Also, how can a different action be triggered on click? LATEST I was specifically referring to using the jQuery UI accordion widget for this functionality. ...

The method xxx is not defined within my ViewModel

Why am I encountering an error Uncaught TypeError: this.createRow is not a function when constructing the matrixLengthsAvailable array? The createRow function is defined at the end of my viewmodel... function TabBuyHarvesterModel() { self = this; ...

Encountered an error while attempting to proxy request from localhost:8000 to http://localhost:4000. Connection refused (ECONNREFUSED) was the cause of the issue

Trying to build a Gatsby App with the help of this Starter kit found at this GitHub link But every time I update my node packages and run Gatsby Develop, I encounter an HPM Error when trying to access my page. The project compiles without any issues, but ...

Styling extracted content using headless browsing algorithm

Is there a way to format the scraped text from multiple elements on the page for use elsewhere? I have JavaScript code that can loop over the elements, add their text to an array, and turn it into a string, achieving the desired formatting. How can I inc ...

What is the method for retrieving the input text value contained within a select option?

I have encountered an issue in my HTML template where I am unable to retrieve the value within the input field upon submitting, especially if a custom category name was entered. The code includes an HTML <select> and <input> fields: {% for i ...

Stopping all animations with JQuery animate()

I have a question about stopping multiple animations. Here's some pseudocode to illustrate my situation: CSS #div1 { position: absolute; background-image: url("gfx/cat.jpg"); width: 60px; height: 70px; background-size: 50%; b ...

What is the best method for sending the primary key value to DynamoDB?

I am currently working on a nodejs app where I am using putItem() to insert data into DynamoDB. The table has a primary key named "id". My goal is to generate a UUID and assign it as the value for the primary key every time new data is inserted. However, w ...

Guide on replacing empty values, marked as "", at the corresponding index with values from a separate array

In need of help with two string arrays that have the same size, but different values: arrayAlpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] ...

What is the best way to retrieve the UTC value of a specific date and time within a particular time zone using JavaScript?

I want to create a Date object with a specific time: "Midnight in Los Angeles on Christmas 2011". Although I've used moment.js, which is good, and moment-timezone, which is even better, neither the default Date class nor moment constructors allow for ...

Obtaining a pdf file using javascript ajax is a straightforward process

Looking to access my JavaScript file generated by a microservice (byte[]): public int retrieveLabel(Request request, Response response) throws IOException { response.header("Access-Control-Allow-Origin", "*"); ArrayList<JSONObject> orders = ...

The current date is indicating that the date string provided is invalid for interpretation by dayjs()

Have you tried using DayJs? If you're working on the browser, specifically with Firefox + Vue + typescript, here's my date string: 2021-02-05 12:00 AM However, when I include the AM/PM in the code like this: const dateObj: any = dayjs('2 ...

boosting the maximum number of requests allowed

What can be done to increase the request limit if the user continues to hit rate limits? This is my current rate limiter setup: const Limiter = rateLimit({ windowMs: 10000, max: 5, standardHeaders: true, legacyHeaders: false, keyGenerator: funct ...

Is there any variation in the Stripe payments Workflow when utilizing the Connect-API?

I have a question about simplifying the implementation of the Stripe API for multiple products on a single page. Currently, I have a webpage with 20 different items and I am utilizing Stripe Connect. Instead of creating individual forms for each product i ...