Checking for partial matches in JavaScript using includes()

I've encountered a problem while comparing a string of numbers to ids in a JSON file using JavaScript to generate a favorites list. I'm utilizing the includes() method to check if the tourid in the JSON file matches any of the numbers in the string.

The issue arises when dealing with larger numbers in the array. If the list contains 34, only the details for tourid 34 are displayed. However, if the list includes 134, both tourid 34 and 134 details are shown. I've also experimented with indexOf() which yielded similar outcomes.

Is there a way to make includes() strictly look for exact matches?

Below is the script (and yes, it's within a worker script hence the postMessage at the end):

function getMyLst(mylst) {
  // Creating nav list from myList array

  // Check if mylst is empty
  if (mylst === '') {
    let myLstStr = 'rmvml|0';
    postMessage(myLstStr);
  }
  else {

    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var myLstStr = 'mylst|';
        var lstCnt = 0;
        var daLst = '';
        var clipList = '';
        data = JSON.parse(this.responseText);
        // Iterate through to find matches and build string
        for (let i = 0; i < data.length; i++) {
          if (mylst.includes(data[i].tourid)) {
            myLstStr += '<a href="'+data[i].url+'">'+data[i].tourname+'</a><br>';
            lstCnt++;
            daLst += (data[i].tourid)+',';
            clipList += data[i].tourname+' - '+data[i].url+'\n';
          }
        }
        myLstStr += '|'+lstCnt+'|'+daLst.slice(0, -1)+'|'+clipList;
        postMessage(myLstStr);
      } 
    };

    xmlhttp.open("GET", dturl, true);
    xmlhttp.send();

  }
}

The onmessage function within the worker, wherein mylst values are sent as a comma-separated string: mylst|146,57,134

onmessage = function (e) {

  // Identifying worker function from first variable
  // Remove first value before "|"
  let msg = e.data[0];
  var val = msg.split('|');

  // Fetching myList data
  if (val[0] === 'mylst') {
    var mylst = val[1] ;
    getMyLst(mylst);
  }
  // End of myList section

Answer №1

The issue at hand arises from the behavior of the includes() method in JavaScript, which searches for a substring within a string. This means it can return matches not only for exact matches but also for partial matches.

To ensure that includes() only looks for exact matches, you can modify your code to compare values using the === operator instead.

Replace the line

if(mylst.includes(data[i].tourid))
with
if(mylst.split(',').includes(data[i].tourid.toString()))
to guarantee an exact match between values. The split() function is used to convert the comma-separated string into an array, while toString() ensures a string comparison.

solution:

function getMyLst(mylst) {
 // create navigation list based on myList array

 // check if mylst is empty or contains numbers
 if (mylst === '') {
  let myLstStr = 'rmvml|0';
  postMessage(myLstStr);
 }
 else {

let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    var myLstStr = 'mylst|';
    var lstCnt = 0;
    var daLst = '';
    var clipList = '';
    data = JSON.parse(this.responseText);
    // iterate through and build the string if in mylst
    for (let i = 0; i < data.length; i++) {
      if (mylst.split(',').includes(data[i].tourid.toString())) {
        myLstStr += '<a href="'+data[i].url+'">'+data[i].tourname+'</a><br>';
        lstCnt++;
        daLst += (data[i].tourid)+',';
        clipList += data[i].tourname+' - '+data[i].url+'\n';
      }
    }
    myLstStr += '|'+lstCnt+'|'+daLst.slice(0, -1)+'|'+clipList;
    postMessage(myLstStr);
  } 
};

xmlhttp.open("GET", dturl, true);
xmlhttp.send();

} }

I trust this solution will work effectively for you, but if any issues persist, please do inform me :)

Answer №2

utilize the string.search() method instead

it will distinguish between 34 and 134, only selecting the unique values while also supporting the use of regexp

const dataset = [
  {
    id:34
  },
  {
    id:134
  },
  {
    id:234
  }
];

let dataList = '146,57,134,34';


for (let i = 0; i < dataset.length; i++) {
  const contains = dataList.search(dataset[i].id)>0?true:false;
  if (contains) {
    //perform an action
    console.log('I am in',dataset[i].id)
  }else{
    console.log('I am not present',dataset[i].id)
  }
}

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

Create a new JSON array by filtering this JSON array based on a specific date range

Having a json array that contains the following keys and values: { "results": [ { "date": "2013-15-5", "position": "23", "race" : "2" }, { "date": "2013-15-6", "positio ...

Adjusting Countdown.js functionality

I stumbled upon countdown.js after coming across this helpful resource: My knowledge in JavaScript is limited, and I'm looking to configure the countdown to start exactly a week from today, which would be on February 24, 2014. Is there a way to twea ...

Generate a request to load JSON data

On my webpage, I have several external JSON files that need to be loaded. I'm looking for a way to specify the order in which they should be loaded. Using JavaScript for this task, here is an example: const func1 = () => { $.getJSON(json1, re ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

One way to integrate social sharing buttons into your Django blog

I am currently using the django_social_share module and I am struggling to understand how to send the sharing URL for a specific blog post on social media. Here is my post_detail.html: <article> <div class="embed-responsive embed-responsive-1 ...

Updating NPM yields no changes

Having trouble updating dependencies in a subfolder of my MERN stack app. Specifically, I am trying to update the dependencies in the client folder where the React code is located. However, when I attempt to update the dependencies in the client folder, it ...

Loading a page with a subtle fade-in effect using jQuery

Looking to add some jQuery functionality to my navigation menu in order to have the page wrapper fade in and out when a main nav link is clicked. While the code itself is functioning properly, I am encountering a couple of issues: There is a brief flash ...

Creating a Graph of Word Lengths in C Programming

Currently tackling exercise 1.13 in Kernighan and Ritchie's "The C Programming Language," but hitting a roadblock with my program - it's not producing the expected output. The challenge at hand is outlined below: Exercise 1-13. Develop a prog ...

Challenges with using JavaScript arrays

I'm facing a major issue with my website. As someone who is new to JavaScript, I am attempting to utilize an array for storing different responses based on the input provided in a text box. The template I am working with can be found here. Although t ...

Press the "submit" button to perform an onclick event just before the form's "action" is executed

Here is a form that allows you to select a CSV file and upload it to a MySQL server: <form class="ui input" enctype="multipart/form-data" method = "POST" action="trend_upload_csv.php" role = "form"> <input type = "file" name ="file" id="file" ...

Animate the jQuery display property to show a table without changing any specified spatial dimensions

When utilizing jQuery's $.animate() on an element styled with display:table, any spatial dimensions that are not explicitly specified to change will animate. Check out the fiddle here In the scenario presented, the width is defined for animation, bu ...

Guide on how to show the index value of an array on the console in Angular 2

Is there a way to show the array index value in the console window upon clicking the button inside the carousel component? The console seems to be displaying the index value twice and then redirecting back to the first array index value. Can we make it so ...

What is the best way to compare two 2D arrays in JavaScript?

Having an issue comparing two 2D arrays in javascript, looking to output "true" if the arrays are the same. This is the code I experimented with: ` function check(){ if (data.every() === solution.every()){ alert("example"); } else { ...

When using res.redirect in Express, it not only redirects to a new URL but also allows you to access the HTML

I'm having an issue with redirecting a user to a login page when they click a button. Instead of being redirected, I am receiving the html source code and nothing is happening. My express redirect method is as follows: function customRedirect(req, ...

I am experiencing an issue with my localhost website where the images only display after I open the files in VScode. Is there a way to load the images correctly using app.js?

app.js While working on web development in VScode, I've encountered an issue where the images on my localhost website only appear after opening files like home.pug and contact.pug alongside app.js. Is there a way to make the images load properly witho ...

Implementing a feature in jQuery to reveal an element upon button click

I need to create a functionality where clicking a button will display a panel. Initially, I have set the panel's visibility to false in its properties. So, when the user clicks the button, the button should hide and the panel should show up. How can I ...

Is it feasible to send an AJAX POST request to a server with a distinct domain while utilizing basic authentication?

I have encountered an issue while attempting to send a POST request to a server with a different domain that necessitates basic authentication. Despite my best efforts in experimenting with beforeSend and withCredentials, the basic auth headers do not get ...

Unconventional login processes showcased in Redux-Saga's documentation

When looking at the login flow example in the redux-saga documentation, it is clear that the expected action sequence is well-defined. However, does the LOGOUT action always follow the LOGIN action? In real-world scenarios, such as when a user's sessi ...

Arrange the array of days and months in JavaScript

Attempting to rearrange a date Array from newest to oldest has proven challenging as the list.sort function only rearranges based on the initial number. The Array in question is as follows: var MyArray = ["13 Jun", "09 Jun", "25 Aug", "30 Jun", "13 Aug"]; ...

Searching for a specific word within a given string using a loop

Currently, I'm developing a 'for' loop to search for my name, Andrew, in a given text and store the occurrences in an array. However, there seems to be an issue with the implementation. /*jshint multistr:true */ var text = ("Andrew is real ...