Iterating through an array with conditional statements

I am currently considering the best approach to loop through an array in my code before proceeding further. I have some concerns about the link (var link = ... ) and the if statement.

Is this the most optimal way to iterate over array1 and compare the values to those in array2? If my code is correct (which I am unsure of at the moment), is there a more efficient way to achieve this?

Furthermore, I am curious whether this loop will run through every element of array1 indefinitely or just one of them indefinitely.

var array1 = [741, 451, 54188, 5847, 5418, 54944, 310, 541, 7451, 10211, 113, 9115, 62, 2841, 52482481, 24];
var array2 = [15, 418, 488, 130000, 8482, 55, 16, 14, 2546, 651, 4521, 11, 54, 659, 542, 1152];

var myObj = {};
array1.forEach(function(item, i) {
    myObj[item] = array2[i];
});

var Loop = setInterval(function(){ 
    for (var prop in array1) {
        var link = "http://blahblahblah.com/blah/" + array1[prop] + "/blahblah"
        $.get(link,function(data){
            var dataGiven = $("span.cost-in-usd:first-child").text();
            dataGiven = Number(dataGiven.replace(",",""));
            dataGiven = Number(dataGiven.replace("(",""));
            dataGiven = Number(dataGiven.replace(")",""));
            if (dataGiven <= myObj[prop]) {
                //stuff happens
            }
        });
    }
},0)

Answer №1

The for in statement is typically used to iterate through properties of an object. While it can sometimes be used with arrays, a more appropriate method is shown below:

for (var i = 0; i < array.length; i++) {
    var value = array[i];
    // Perform actions here
}

In response to the latter part of your query, using an interval to loop through an array would result in an infinite loop situation. It is unnecessary to set an interval for looping through an array as it would essentially loop through the entire array every 0 milliseconds.

Answer №2

If I were in your shoes, here's how I'd approach it:

for (let i = 0; i < array1.length; i++) {
    if (array1[i] <= array2[i]) {
        //Take necessary action
    }
}

forEach can also be used as an alternative method.

In regards to your query about var link = ..., as long as it is a correct path and you remember to end it with a semicolon, you should be fine.

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

Concatenating strings with JavaScript

I am currently working on building a web page using a combination of html and javascript. I have a json file that provides inputs for some specific content I need to display. My main goal is to set up an address variable in order to show the Google Maps AP ...

Show a brief glimpse of the JS/jQuery object on the screen

Exploring JavaScript objects today and encountered an unusual glitch. <form method="get" action="" name="start" > <fieldset> <label for="date">Date</label> <input type="date" name="date" id="date" /> <div>&nbsp; ...

The link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

Using ng-repeat with ng-model; accessing the value of ng-model

I find myself in a peculiar situation - Behold the Controller snippet - $scope.filterNum = {0: 'filterVal1', 1: 'filterVal2', 2: 'filterVal3', 3: 'filterVal4', 4: 'filterVal5', 5: 'filterVal6', ...

Is there a method available for us to successfully deliver an email to the user who has been registered?

I am currently working on the registration page for my React app. One of the requirements is to send a confirmation email to the user's email address once they have registered. The user's account will only be confirmed once they click on the veri ...

Node.JS has deceived us with its false promises of `import` support

Could it be that I am making a mistake? I have been eagerly awaiting the experimental ES6 module loader in Node.JS since version 10. This feature is crucial for me to seamlessly use the same code in both the browser and node environments. This is how I w ...

Convert the list items into JSON format

<div class="col-xs-4 no-padding contenteditable-color" style="background-color: transparent;"> <ul class="ul-product"> <li class="li-product-page cars contenteditable" contenteditable="false">qweryt</li> </ul&g ...

Substitute "Basic Authentication" with "Form Authentication"

Is there a way in W20 to switch from using "Basic Authentication" to "Form Authentication"? The current documentation mentions only the use of "basicAuth" and does not provide information on implementing form authentication. Our app is built with Angular ...

JQuery grid pagination bar mysteriously missing

I'm having an issue with a Jquery grid that is built on an HTML table. I've properly configured the grid properties, including implementing pager functionality with a page size of 10. However, I am unable to see the page up and page down buttons ...

Develop a responsive shopping cart using PHP and JavaScript

I am in the process of developing an ePos system that allows users to add items to their basket by simply clicking on them, and then calculates the total price without needing to refresh the entire page. I initially attempted to use $_SESSION and store th ...

Using NodeJs to pass values to a callback within a condition statement and retrieve the returned value

Within my routing file, I have implemented a condition where an external function is used to compare two values: obj.id === getId. Based on whether this condition evaluates to true or false, the view is rendered, or the user access is blocked. The functio ...

Activate the element by simulating a button click on another element

I created a "copy-button" component that is utilized in various parts of the application, allowing users to copy information to their clipboard. This component has two bindings: buttonText and buttonClass, which can be used to customize the text displaye ...

Show information upon opening

I am currently working on a project that involves 4 different divs, and I need the content of each div to be displayed based on dropdown selection. I found a code snippet that was close to what I needed, but after trying to adjust it, I haven't been a ...

Output certain elements from an array and then incorporate them into an if-else statement

I am currently working on developing an on and off switch that is based on an item within an array. The data has already been extracted from JSON, so now I just need to work with the array. This array has been generated from an API call and is returned in ...

What is the best way to incorporate dynamic data from Firestore into a function using the `where()` method, while also utilizing the `snap.size` property to accurately count the total number of queries

I am facing an issue while trying to fetch data dynamically from firestore using a where() function. The specific error message I encountered is: TypeError: vaccines is not a function The user collection: [![enter image description here][1]][1] Here a ...

Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise. I can provide my code if necessary, but I'm aiming to achieve something sim ...

"Learn how to smoothly navigate back to the top of the page after a specified amount of time has

Just starting out with JS, CSS, and Stack Overflow! I'm currently working on a div box that has the CSS property overflow: auto. Is it possible to make the box automatically scroll back to the top after a certain amount of time when the user scrolls ...

What is the best way to modify a constant array in Angular?

Hello team, I'm fresh to working with angular and I have a TypeScript file that contains a list of heroes: export const HEROES: Hero[] = [ { id: 11, name: 'Dr Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombas ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...