Ways to search for and compare items within an array obtained from the results of a loop once the loop has finished executing in JavaScript

I am encountering an issue with my JavaScript code while working on a reminder app in Cordova and using the Katzer notification plugin. My goal is to implement a feature where, if a user tries to add a reminder that already exists, an error is thrown. Conversely, if the reminder does not exist, it should be added to the list of reminders. I am currently facing a challenge with my JavaScript loop in achieving this. Here is a snippet of my code:

function checkIfReminderExists(){

 cordova.plugins.notification.local.getAll(function (notifications) {

     var allRemindersInfo = "";
     var newAllRemindersInfo = "";

     // using a while loop  
     var count = 0;

     while (count < notifications.length) {

         cordova.plugins.notification.local.get(count, function (notification) {

             allRemindersInfo = allRemindersInfo + notification.text;

             if(allRemindersInfo.indexOf(""+checkedBoxes+"") == true) {
                 alert("Sorry, you cannot add a reminder that already exists...");
             } else {
                 alert("There is no similarity, so I am going ahead to create the reminder now...");
                 setLecReminders();                       
             }
          });

         count++;
         continue;
     }  

});   

}    

/* The above method did not work, so I tried using a for loop to address the issue */

function checkIfReminderExists(){

 cordova.plugins.notification.local.getAll(function (notifications) {

     var allRemindersInfo = "";
     var newAllRemindersInfo = "";
     var count;

     for(count = 0; count < notifications.length; count++) { 

         cordova.plugins.notification.local.get(count, function (notification) {

             allRemindersInfo = allRemindersInfo + notification.text + ", ";
             newAllRemindersInfo = new Array(""+allRemindersInfo+"");

             if(newAllRemindersInfo.indexOf(""+checkedBoxes+"") == true) {
                 alert("Sorry, you cannot add a reminder that already exists...");
             } else {
                 alert("There is no similarity, so I am going ahead to create the reminder now...");
                 setLecReminders();                      
             }
         });
     }

});   

}

I have tried both the for and while loops mentioned above, but unfortunately, none of them provided the desired result. Instead, the "if()else" test runs separately for each loop iteration. This causes a challenge where the setLecReminders() function executes regardless of the subsequent test results, leading to undesired outcomes. I am seeking a solution where the loop completes first, all items in the list are stored in an array, and then a simultaneous if()else test can be performed on all members of the array. Apologies for the lengthy question and thank you in advance.

Answer №1

To enhance your loop, I recommend incorporating a boolean variable like so:

    var duplicateReminder = false;
    while (counter < notificationsList.length)
    {
        cordova.plugins.notification.local.get(counter, function (notification) {
            allRemindersInfo = allRemindersInfo + notification.text;
            if (allRemindersInfo.indexOf(""+selectedCheckboxes+"") == true)
            {
                duplicateReminder = true;
            }
            counter++;
    }

After the loop, evaluate the boolean value and display alerts accordingly:

    if (duplicateReminder) {
        alert("Apologies, you cannot add an existing reminder...");
    } else {
        alert("No similarities found, proceeding to create the new reminder...");
        setNewReminders();
    }

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

Tips for simultaneously updating a value in multiple collections on firestore?

Currently, I am in the process of developing a forum application using Vue, which is essentially a replica of this platform. In this app, users can post questions, receive answers to those questions, and leave comments on those answers. Each question, answ ...

Alternative for Jquery: a new Hash Table solution using Prototype JS

Greetings everyone! I have experience as a prototype JS developer but now I am transitioning to jQuery for work/client reasons. One feature I really liked in Prototype was the Hash class, such as var h = new Hash();. However, I understand that jQuery doe ...

Tips for swapping out the content within a "li" element

I am dealing with a situation where I have approximately 100 pages, all containing an <ul> tag, but the issue is that I need to enclose each list item within a <span> tag. Below is the code snippet I have tried: <ul style="list-style-type: ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

Show information from an array

On the index.php page, there is a script that retrieves data from demo.php and presents the outcome in a div. <div class="leftbox"> <?php echo "<div id='proddisplay'>"; echo "</div>"; ?> </div&g ...

Toggle visibility with jQuery's Show & Hide feature

Currently, I am working with some divs that need to be hidden (with the class .hideable) and others that need to be shown (with the class .toggleable). I have made progress in getting everything to work as desired. However, I am facing a challenge - once t ...

How to generate a summary column in SAS using data from various columns

I am looking to generate a condensed single column in SAS that summarizes multiple columns for each individual within a data set. The data structure is as follows: Subject VisitNumber Exam Result Comments 001 1 Blood ...

The mouse movement event will not be triggered for every frame when a keyboard event occurs

When the mouse is moving in a browser, ideally the mousemove event should fire every frame. However, if a key is pressed or released (or repeated), the mousemove event stops firing for a frame or two. To test this behavior, you can use the code snippet bel ...

How to extract column name from query result set using JavaScript in Snowflake database?

When querying in Snowflake with JavaScript inside a stored procedure, we typically receive a Result_set. How can the column names of the output result be retrieved using the JavaScript API? Please note that this inquiry is not about retrieving the values ...

What is the best way to invert the positioning of the li elements to move upwards?

https://i.stack.imgur.com/mZaoS.png Seeking assistance on adjusting the height of bars to start from the bottom and go upwards instead of starting from the top position and going downwards. The JavaScript code below is used to generate the li elements and ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

Using JavaScript to create temporary drawings on a webpage that automatically erase themselves

I am curious about how to achieve a scribble effect that self-erases, similar to what is seen on this website: Example: Thank you! I have come across some similar scripts, but I am struggling to understand how to make the scribble disappear after a few ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Executing a C# method from within a .js file using a Javascript function in a .cs file

I've made some updates based on the responses provided. My main area of confusion lies in the 'data' parameter and how to handle it in the JavaScript call. C# method [HttpPost] public string GetPreviewURL(string activityID) ...

The clingy navigation bar hinders smooth scrolling to the content

My website has an image where users can click on elements to scroll down to text. However, I'm facing a problem because there is a sticky menu at the top of my website. How can I ensure that the scrolling works correctly with the sticky menu included? ...

Encountering the issue of "Unknown provider" while injecting Angular modules

After following a tutorial on organizing an Angular project, I came up with a structure where I have a ng directory containing all my controllers, services, and the routes.js file. These are then bundled together into an app.js through my configuration in ...

Watching a service's attribute from within a route in the EmberJS framework

There seems to be a concept that I'm struggling to grasp here. To my understanding, any instance of Ember.object should be able to observe properties on another instance of Ember.object. In my scenario, there is a service, a router, and a component i ...

Prevent a form from loading depending on the response received from an ajax callback

I am currently working on implementing an ajax post function. The process involves sending data and receiving a callback from PHP with some data in return. Depending on the returned data, I need to make a decision whether to proceed or allow the user to re ...