What is the proper way to search for a specific string within a JavaScript array during an iteration?

I am working with an array that is continuously updated with new string elements every 2 seconds. The code snippet below showcases how the updates are processed:

//tick world
setInterval(function(){
  doTradeUpdate();
},5000);

function doTradeUpdate(){
  var randyManu = Math.floor(Math.random() * 10);
  switch(randyManu){
  case 0:
  //new duro mine
  countPush(manufacture,"duro-mine");
  break;

  case 1:
  //new e-plant
    countPush(manufacture,"e-plant");
    break;
//etc
}

function countPush(arrayz,addable){
  console.log(arrayz);
  console.log("Attempting to add: " + addable);
  if(arrayz.length == 0){
    arrayz.push(addable);
  }
  else{
    if (arrayz.indexOf(addable)  > 0){
       console.log("FOUND");
    }
    else{
        console.log("NOT FOUND");
        arrayz.push(addable);
    }
  }
}

However, an issue arises where sometimes the code outputs "FOUND" and other times "NOT FOUND" for the same array element, like "e-plant". Consequently, multiple duplicate entries can exist within the array. What could be causing this inconsistency in matching elements?

This script is solely responsible for handling the array updates.

Thank you!

G

Answer №1

implement

if (arrayList.indexOf(newValue) !== -1)
{
  console.log("VALUE FOUND");
}
else
{
  console.log("VALUE NOT FOUND");
  arrayList.push(newValue);
}

For a more optimized approach, consider using (!== -1) instead of (> 0).
It's worth noting that if the element is in position 0 it will return "VALUE NOT FOUND". You can enhance the code further as shown below

function updateArray(arrayList, newValue)
{
console.log(arrayList);
console.log("Attempting to add: " + newValue);
if(Array.isArray(arrayList))
{
  if(arrayList.indexOf(newValue) !== -1) {
    console.log('Element exists in the list');
  }
  else {
    arrayList.push(newValue);
  }
}    
}

There are more efficient ways to check if a variable is an array, this is just a simple example!
Also, consider storing the array in a common outer namespace instead of passing it every time if it remains the same in both function calls.

Answer №2

Give this a shot

 let targetIndex = arrayz.indexOf(addable);
if (targetIndex > -1) 
{
    console.log("Item is FOUND");
} 
else 
{
    console.log("Item is NOT FOUND");
    arrayz.push(addable);
}

Answer №3

In the event that the element cannot be located, the function will return -1, causing your validation to fail as it mistakenly checks if the index is greater than 0.

To rectify this, ensure that you check:

(arrayz.indexOf(addable) !== -1)

Answer №4

indexOf() will return -1 if the element is not found. If it returns 0, it means the element is found in the first position of the array, which may not be the desired outcome.

It is recommended to modify the code from

if (arrayz.indexOf(addable) > 0)

to

if (arrayz.indexOf(addable) > -1) 

Alternatively, you can combine your conditions to simplify the logic:

function countPush(arrayz, addable) {
    console.log(arrayz);
       console.log("Attempting to add: " + addable);

       // Same as nested if statements, due to short-circuiting
       if (arrayz.length === 0 || arrayz.indexOf(addable) === -1) {
           console.log("NOT FOUND");
           arrayz.push(addable);
       } else {
           console.log("FOUND");
       }
}

Answer №5

give this a shot

(arrayz.indexOf(addable) !== -1)?(console.log("ITEM FOUND")):((console.log("NOT FOUND")) || (arrayz.push(addable))); console.log(arrayz);

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

Fetching images from directory in xcode

I'm encountering difficulties loading images from a file into an array. I've tried different methods found online but still haven't found a solution. Being new to objective-c and a bit rusty on the rest, I could really use some guidance. In ...

Configuring settings for gulp-jshint

I'm currently utilizing gulp to compile my JavaScript code. My intention is to run jshint on the files before concatenating them, but I'm encountering difficulties in configuring the options properly. Am I handling this process correctly? var re ...

What could be causing my function to output unicode replacement characters instead?

As I work on enhancing password security by implementing encryption, my goal is to store the hashes and perform encryption/decryption during signup/login processes. The encryption process works smoothly, converting from utf8 to hex without any issues. Howe ...

What is the best way to show the initial 20 words on the screen, followed by the next 20 words using

Within a single tag, I have a string as shown in the example below. My goal is to display the first 20-25 words on screen, then continue with the next set of words, and so forth. Once 20 words are displayed, the remaining text should be hidden. <p>Lo ...

I am looking to transfer an image stored in a database onto a card

One issue I am facing is that when trying to display an image from a database, uploaded by a user and showing on a card with additional information like name and price, an icon resembling a paper with green appears in the output. Here's my code snippe ...

Drop and drag the spotlight

On my website, I am looking to implement a feature that will make it easier for users to identify the drag and drop area. I found a code snippet on JSFIDDLE that works perfectly there. However, when I tried to use it on my local server, it doesn't se ...

Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below: var marker = new google.maps.Marker({ position: new google.maps.LatLng(-25.363882,131.044922), map: map, title:"Hello World!", icon: CanvasCrear("hola", 15) ...

What are the steps to create an endless scrolling feature?

I'm trying to create a slider with a horizontal scrolling effect, but I've hit a roadblock. How can I make the slider scroll infinitely? In my code, you can see that after Item 6, it stops scrolling and I have to scroll backward. However, I want ...

What is the process for incorporating beforeAnimate and afterAnimate callbacks into a custom jQuery plugin?

Let's imagine I have developed a plugin: // creating the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} ...

Utilizing an AngularJS service to communicate with a web API

Having trouble retrieving data from a web api and passing it back to a JavaScript file. I've tried using http://localhost:8584/api/Testing/5 to see if there are any results, but no luck so far. //This is the JavaScript controller that calls the serv ...

Initiate a POST request to download the file upon clicking the button

How can I initiate a file download when a button is clicked? During testing, I noticed that sending a GET request using <Link href="/api/generate-pdf"> works perfectly and the PDF file gets saved. However, when I use a button to hit the API, the dow ...

Removing a single duplicated element from an array using jQuery

I'm facing an issue where if I try to remove the first element that I added using the button, all elements in the array get erased. However, when I remove the last element pushed, it works just fine. To tackle this problem, I attempted to use $.inArr ...

Working with a two-dimensional array in Java: printing values using a for loop

I'm attempting to create a two-dimensional for loop that will display the following pattern: 7 5 3 1 2 4 6 8 Below is my array: int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}}; The current for loop provided only prints one number ...

Using Vue to fetch JSON data with Axios

When trying to retrieve user data from a MongoDB in JSON format using axios.get within a Vue.js application, my aim is to visualize this data by iterating through all user objects in the users array. The issue I'm facing is that each character is trea ...

Is it true that IE does not support passing callback parameters to setTimeout()?

When I used the js setTimeout function in my code, it worked perfectly in Firefox by reloading within seconds. However, the same code did not work in IE. I tried changing the method to 'POST', but received an error stating that the request was no ...

Ensure that each of the two divs maintains a 16:9 aspect ratio, and utilize one div to fill any remaining empty space through the

This layout is what I am aiming for: https://i.sstatic.net/uZdty.png While I can achieve a fixed aspect ratio with a 16:9 image by setting the img width to 100%, I run into an issue where the height scaling of flexbox becomes non-responsive. The height re ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

Express-session is failing to return a value in spite of my explicit declaration of the session

I've been working on my website for quite some time and everything was smooth sailing, until now. Here's the issue: after a user logs in, a session cookie named "user" is created to store their email. Upon console logging the cookie right after ...

Sift through JavaScript problems

My goal is to implement a filtering function on my input that will display a different result. However, I have encountered an issue where the this.data.stationInfo.stations array is being changed, as shown in the console.log output. According to the Mozil ...