How do you find a specific value in an array using a function?

As a newcomer to JavaScript and StackOverflow, I am currently working on creating a function to search for a specific value within an array I have created. Although I have written what I think is a functioning function, it seems to not be working. Any ideas or obvious flaws you can spot? Thanks!

HTML:


<td>Index: <input style = "width: 50px" input type ="textbox" id="Index"  value="2"/></td> <!-- HTML code to create the index textbox -->
<br/> <!-- Line Break -->
Value: <input style = "width: 50px" input type = "textbox" id="Value" value = "10"/> <!-- HTML code to create the value textbox -->
<br />
<td>Enter Value to Find: <input style="width: 50px;" type="textbox" value="20" />
<input type="button" value="Search Array" onClick = searchArray(); /></td>
<br />
<input type = "button" value = "Create" onClick = "createArray();"/>
<input type="button" value="Insert into Array" onClick="insertIntoArray();" />
<div id="result">

JS:

var myArray = [];
var d = ""; //This global variable is going to be used for clearing and populating the screen 

function createArray (){
    //This functions is to clear the current information on the screen so the array can populate
  clearScreen(); 
  //The next thing we want to do according to the lecture is create a FOR loop to run 100 times to set the various array values
  for (var i = 0; i <100; i++){
  myArray[i] = Math.floor(Math.random()* 100 + 1); //Math.floor rounds an number downards to the nearest integer then returns. Math.random returns a        integer randomly withing given variables
  }
  popScreen(); //function to fill the screen with the array 
}


function clearScreen(){
d = ""; //Global string variable mentioned before 
document.getElementById("result").innerHTML = "";
}


function popScreen(){
    for (var i = 0; i < myArray.length - 1; i++){
    d += i + ' : ' + myArray[i] + "<br/>";
  }
  document.getElementById("result").innerHTML = d;
}


function insertIntoArray(){
    clearScreen();
    var i= parseInt(document.getElementById("Index").value);
        var j = parseInt(document.getElementById("Value").value);
d = "inserting " + j+ " at " + i + "<br/>";
    
    var temp = myArray[i];
        for (i; i < 100; i++) {
        myArray[i] = j;
      j = temp
        temp = myArray[i+1];
      }
    popScreen();
}

**function searchArray(myArray, value){
  var searchResult = 0;
  var searchIndex = -1;
  for(var i = 0; i<myArray.length; i++){
    searchResult++;
    if(myArray[i] == value){
        searchIndex = i;
      break;
    }
  }
  
  if (searchIndex == -1){
    console.log("Element inquiry not found in array. Total Searched: " + searchResult);
  }else{
    console.log("Element found at index: " + searchIndex + ", search count: " + searchResult);
    }**
  }

Answer №1

An issue arises due to the absence of arguments being passed to the searchArray function through the inline onclick attribute, which are essential for its operation.

A TypeError is thrown: Unable to read properties of undefined (reading 'length')

This error occurs because the variable myArray is undefined and therefore does not possess a length property.


To resolve this, the HTML needs to be adjusted as follows:

<input type="button" value="Search Array" onClick = searchArray(); />

should be changed to:

<input type="button" value="Search Array" onClick = searchArray(this); />

The corresponding function should then be modified like so:

function searchArray(element) {

  let value = element.previousElementSibling.value
// remaining code unchanged

Since searchArray is already declared globally, there is no need to pass it as an argument. However, accessing the value from the input preceding the button is necessary. This can be achieved using the previousElementSibling method.

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

"Assure that setTimeout will be executed within the then method in

Within an Immediately Invoked Function Expression (IFFE), I am returning a Promise. The first thing that is logged is first, followed by third, and then second. Despite having the setTimeout inside the then block, shouldn't everything within it be exe ...

Changing JavaScript array elements from strings to objects

While working with React, I am facing a challenge in creating an order/sort array to be sent to Node.js. The situation demands sorting by a specific table column. Here is what I have in React: sort = `[[Contact, "phone1", "asc"]]` This ...

Using array.map() in React does not display elements side by side within a grid container

I'm currently working with React and material-ui in order to achieve my goal of displaying a grid container that is populated by an array from an external JavaScript file. The challenge I am facing is getting the grid to show 3 items per row, as it is ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

Stop Antd Modal from automatically scrolling to the top

At the moment, I'm utilizing Ant Design (v4.22.8) and Next.js (v12.3.4) in my project. One issue I've encountered is with a Modal component that activates when a button is clicked. Instead of overlaying the current content on the screen, the moda ...

What are the implications of storing data on the browser in the form of a JavaScript array?

Below is the code I have written: var back_arr = [], forward_arr = [], i = 1; $('button').on('click', function(){ var new_value = $('input').val(), old_value = $('.content').html(); i = i + 1; ...

Analyzing exif data during the process of uploading a batch of images

My website allows users to upload multiple images simultaneously. I want to check the EXIF rotation tag of each uploaded image in order to manually rotate the images in the browser if needed. I came across a solution for reading the EXIF rotation value of ...

Why does the select element display the first item when it is bound to a model?

I'm facing an issue with a select element in Angular6. I have a situation where the options in the select are dynamically generated based on an array that undergoes changes through a pipe. When the selected value in the model is no longer present in t ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...

Organizing layers with Leaflet's layerGroup controls

I am working with a series of Leaflet FeatureGroups, each made up of GeoJSON layers. These FeatureGroups have similar concepts but need to be kept separate for control purposes. I also require the ability to toggle all FeatureGroups on and off simultaneous ...

Utilizing Javascript to collapse the initial DIV element discovered with a specific classname

Seeking assistance with this particular Javascript code. The objective is to collapse the next element. Unfortunately, it is not functioning as expected due to an error in closing the first DIV in each block. The script should aim to collapse the initial ...

Combining the values of duplicate properties to create a new object

I have been working on a task to calculate the total values within an array of objects structured like this: [ { token: 'N97235', conversions: '2', payout: '100' }, { token: 'N91567', conversions: '2' ...

Using a loop to alter the selected value of a dropdown menu with jQuery

Presently, I am using a dropdown menu that displays all the years from 1970 to the current year. Currently, this functionality is achieved through embedded JavaScript within the HTML. My aim is to achieve the same result using an external file and jQuery, ...

Tips for referencing a specific section of a URL within WordPress

Currently, I am in the process of developing a website page with tab-like options. Using buttons and sections of Elementor, I have successfully created the functionality where clicking on each button displays a corresponding section. Now, my goal is to al ...

Guide on Implementing a Function Post-Rendering in Angular 2+

I'm looking to implement some changes in the Service file without modifying the Component.ts or directive file. Here's what I need: 1) I want to add an event listener after the service renders its content (which is generated by a third-party tool ...

Guide on obtaining a refined array result within a document using a mongoose query

I require assistance in creating a query that retrieves specific documents within an array of a main document. The collection stored in the database is as follows: { "_id": "5ed49b42d6fc0c3878c875a2", "stockID": "Stock-1", ...

Issues with Jquery/AJAX function not responding to onChange Event

I am currently working on a project where I need to populate a dropdown menu based on the value selected from another dropdown. However, I am encountering an issue with the function that I am trying to call in the onChange event of the select tag. This is ...

Discovering all information within a defined timeframe

I'm currently working on an iPython notebook where I aim to display a graph of data points within a specific timeframe. Most of the coding is complete, but I need assistance in enabling the selection of a start and end date, after which the program wi ...

Tips for receiving a callback when using the submitChanges method in the telerik grid

When working with the Telerik Grid, I am calling grid.submitchanges()(FUNCTION1) in JavaScript. This call is asynchronous and is followed by an ajax synchronous callback (FUNCTION2). The issue arises when FUNCTION2 gets executed before FUNCTION1 is comple ...

The return false statement is failing to execute properly within this particular JavaScript function

I'm encountering an issue with my onclick function: $("#mymodal").on("click",".close",function() { checkpincode(); checkzipcode(); }); Even though the fn checkpincode returns false, the execution still proceeds and my checkzipcode function i ...