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