JavaScript's search function is encountering issues when working with multidimensional arrays

I have an array containing city names and postal codes that I need to search through. I can successfully search for the city name and retrieve the result, but when I try to search for a postal code, it doesn't register. My question is: How can I modify my search function to accommodate this?

Here's a snippet of my script and array:

Sample of the array:

 Array
 (
[0] => Array
    (
        [0] => 9900
        [1] => Town 1
    )

[1] => Array
    (
        [0] => 9900
        [1] => Town 2
    )

[2] => Array
    (
        [0] => 9940
        [1] => Town 3
    )

[3] => Array
    (
        [0] => 9970
        [1] => Town 4
    )

[4] => Array
    (
        [0] => 9981
        [1] => Town 5
    )
)

 $(document).ready(function(){

  $(".searchinput").keyup(function(){


var b = document.getElementsByClassName('searchinput')[0].value;

var b = document.getElementById("Searchfield")

var SearchValue=b.value;     
var i=0, k=0, indx=[], msg;
for ( i=0; i<postnummer.length; i++) 
  { for ( k=0; k<postnummer[i].length; k++)   
      { if (postnummer[i][k] === SearchValue){ indx = [i,k]; break; }  
  }    }
if(typeof indx[0] == "undefined" || typeof indx[1] == "undefined"){ 
    msg=("Not found"); }
else { msg="i= "+indx[0]+" k= "+indx[1]; }


var a = document.getElementById("Result");

a.value = b.value + " - " + msg ;

    });
});

When I type in "Town 2," I get the expected result: "Town 2 - i= 1 k= 1."

However, I'm unable to retrieve the listing with the "0" index in the array (the postal code 9900) in the result, nor can I search for the number 9900 in the array to return a valid result.

Answer №1

One reason for the issue is that you are utilizing strict equality (===) in your if statement:

postnummer[i][k] === SearchValue

The value returned by b.value is a string (MDN). When inputting "9900" into the input field, the value for SearchValue will also be "9900" as a string, not just 9900

Below is a snippet with the correction made:

$(document).ready(function() {
  $(".searchinput").keyup(function() {
    var postnummer = [
        [9900, 'Town 1'],
        [9900, 'Town 2'],
        [9940, 'Town 3'],
        [9970, 'Town 4'],
        [9981, 'Town 5']
      ],
      b = document.getElementById("Searchfield"),
      SearchValue = b.value, // this returns a string
      i = 0,
      k = 0,
      indx = [];

      for (i = 0; i < postnummer.length; i++) {
        for (k = 0; k < postnummer[i].length; k++) {
          // changed it to ==
          if (postnummer[i][k] == SearchValue) {
            indx = [i, k];
            break;
          }
        }
      }

    if (indx.length > 1)
      console.log(indx)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="searchinput" id="Searchfield" />

Answer №2

If you're looking for an alternative approach, consider using the .reduce method on your array of postnummer to identify the indexes of the search term.

When you input 9900, this function will produce two arrays. The first array will contain the indexes where 9900 is found, and the second array will specify the exact position of 9900.

Check out the code snippet below for a demonstration:

const postnumber = [[9900, 'Town 1'],[9900, 'Town 2'],[9940, 'Town 3'], [9970, 'Town 4'], [9981, 'Town 5']],
  
  search = '9900', /* You can also use 9900 as an integer due to loose comparison in .reduce */
  res = postnumber.reduce((acc, [num, town], i) => {
    if (num == search) return [...acc, [i, 0]];
    if (town == search) return [...acc, [i, 1]];
    return acc;
  }, []);

console.log(res);

Answer №3

When comparing the search value to either a String or a Number, it is recommended to first attempt to convert it to a Number. If the conversion fails (i.e. when using parseInt returns NaN), you can fallback to the original string value:

SearchValue = parseInt(SearchValue) || SearchValue;

Once this is done, you can proceed with using strict comparison:

postnummer[i][k] === SearchValue

This approach allows you to compare the values both as numeric and string values simultaneously.

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

Achieve compatibility for two different types of route parameters in Vue.js

I am trying to set up nested sets of categories in URLs that lead to specific products, but I'm having trouble with matching the routes correctly. Here are the URLs I want: --- renders a "category.show.vue": /$categorySlug+ app.com/catA/cat ...

Issue with JavaScript Onclick Event Handler

Rephrasing Full JavaScript Code. Javascript <div id="PopUp1" style="display: none; color: #FFFFFF;"></div> <div id="Mask"></div> <script type="text/javascript"> var Content = '<p>Content!!!!!</p><input ty ...

The proper method for waiting for a link to be clicked using Selenium

On my web page, I have the following HTML: <a id="show_more" class="friends_more" onclick="Friends.showMore(-1)" style="display: block;"> <span class="_label">Show More Friends</ ...

Group the associative array by determining the maximum value for each pair key

I am working with an array that contains data from objects Array ( Array( 'year' => '2018', 'data' => Array( 'Essence' => [68,54,69,36,36,47,103,97,69,68,0,12], 'Lalo' => [68 ...

Could there be a mistake in the way array combinatorics are implemented in JavaScript?

Having encountered the necessity for generating unique combinations when dealing with multiple arrays, I developed this script. While it functions as intended during the combination process, storing the result in a final array yields unexpected outcomes. ...

Ways to have a React Component trigger a function with each state update

Using this specific component, the getDisplay function is triggered on every update like normal. When the <div> element is clicked, it becomes hidden: class Example extends React.Component { constructor(props) { super(props); thi ...

Is it possible to refresh an iframe with PHP once a certain condition is satisfied?

I have a situation with two pages - one is my PHP script and the other is an HTML page containing two iframes. > <html> > > <iframe name=1></iframe> <iframe name=2></iframe> > > </html> Currently, ifram ...

Is it possible to choose tags from a different webpage?

Imagine you have a page named a.html which contains all the jQuery code, and another page called b.html that only includes HTML tags. Is it feasible to achieve something like this: alert( $('a').fromhref('b.html').html() ); In essence ...

Attempting to retrieve the position of an image within an array upon clicking

function displayGalleryIndex(){ console.log($(this).index()); } $("body").on( "click", "#gallery img", displayGalleryIndex); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="grid- ...

Animation of two divs stacked on top of each other

I am trying to replicate the animation seen on this website . I have two divs stacked on top of each other and I've written the following jQuery code: $('div.unternehmen-ahover').hover( function () { $('div.unternehmen-ahover' ...

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

jQuery function to automatically close any other opened divs when a new div is opened

I have multiple elements that reveal a div when clicked. The issue is that if all elements are clicked, all divs open instead of just the one that was clicked. This is my jQuery code: <script> $(document).ready(function() { $('.servicemark ...

What is the best way to make a JSONP request using jQuery?

Whenever I try to access this API through the browser, everything works fine and I receive the correct response. However, when I attempt to call the API using jQuery AJAX, I encounter an error. *The script is being refused execution from 'http://api ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time. Initially, I set it up like this: localStorage.setItem('example','{"data": []}'); It was working fine, but now I need to structure it like the ...

retrieving request headers using XMLHttpRequest

Is there a way for me to access my requestHeaders within the onload function? Any guidance on how to achieve this would be greatly appreciated. Many thanks! ...

Having Trouble with Typescript Modules? Module Not Found Error Arising Due to Source Location Mismatch?

I have recently developed and released a Typescript package, serving as an SDK for my API. This was a new endeavor for me, and I heavily relied on third-party tools to assist in this process. However, upon installation from NPM, the package does not functi ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

Google Maps API Error: Marker Title Not Found

I am currently developing a map feature that allows users to click on it and generate new markers. These markers should display some information in the sidebar, including latitude, longitude, and a title. The issue I am facing is with the title of the firs ...

Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll. I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll. If anyone has any advice or can poin ...