Determining whether a string includes any elements from an array

Recently, I've embarked on a journey to learn javascript and ventured into developing a small chrome extension. This extension aims to scan item listings on a specific website for products that match keywords provided by users. I am seeking guidance on an approach to compare a string against an array of strings.

Here are the variables in question:

var itemDetails = '[alter] saber 1/8 figure unopened';
var trackingList = ['alter figure', 'magic', 'sword art']; 

The task at hand is to determine if any of the strings in trackingList are present in itemDetails. While I can utilize indexOf() as follows:

function checkArray(str, arr){
   for(var i=0; i < arr.length; i++){
       if(str.indexOf(arr[i]) > -1)
           return true;
   }
   return false;
}

checkArray(itemDetails,trackingList); // returns false

I desire a scenario where a multi-word string like 'alter figure' will return true if all words appear somewhere within itemDetails. Hence, in the above example, checkArray() should evaluate to true since both 'alter' and 'figure' are found in itemDetails.

My current approach involves splitting each element in the trackingList:

function splitTrackList(arr){
    var newarr = [];
    for(var i = 0; i < arr.length; i++){
        newarr[i] = arr[i].split(" ");
    }
    return newarr;
}

trackList = splitTrackList(trackList); 
// [['alter', 'figure'], ['magic'], ['sword', 'art']]

Subsequently, comparison is then made using indexOf():

function newCheckArray(str, arr){
    var passed = true;
    for(var i=0; i < arr.length; i++){
        for(var j=0; j < arr[i].length; j++){
            if(str.indexOf(arr[i][j]) == -1){
                passed = false;
                break;
            }
            else passed = true;
        }

        if(passed) //stop loop if match found
            break;
    }
    return passed;
}

newCheckArray(itemDetails,trackingList); //returns true

While my method yields results, I suspect there might be a more efficient way to achieve this. Your insights and suggestions would be greatly appreciated. Thank you in advance.

Answer №1

Here is a sample code snippet that demonstrates how to search for a specific substring within an array of strings:

Click here for the code

var arr = [
    "cat dog mouse",
    "blue yellow green",
    "pizza burrito hamburger"
];

function isInString(needle, haystack) {
    return new RegExp('\\b' + needle + '\\b').test(haystack);
}

function checkForStringInArray(stringToFind, arr) {
    var inString = false;
    for(var i=0; i < arr.length; i++){ 
        inString = isInString(stringToFind, arr[i]);
        if(inString) break;
    }
    return inString;
}

var inString = checkForStringInArray('yellow', arr);

Answer №2

One method you can utilize is using regular expressions. I will provide an example, although it may not be the most efficient solution.

function checkArray(str, arr){
   for(var i=0; i < arr.length; i++){
       if(str.match((".*" + arr[i].trim() + ".*").replace(" ", ".*")))
           return true;
   }
   return false;
}

In this code snippet, I modify the input string "key1 keyn" to ".*key1.keyn." in order to match those specific keys throughout the string. Keep in mind that this approach will identify them even if they are part of another word. Best of luck with your implementation.

P.S. Understanding and mastering regular expressions is crucial as they play a significant role in almost every programming language.

Answer №3

Here is a solution that should be effective:

function findWordInArray(str, arr){
      for (var j = 0; j < arr.length;j++) {
          wordtab = splitTrackList(arr[j]);
          for(var i=0; i < tab.length; i++){
               if(str.indexOf(wordtab[i]) > -1)
                   return true;
           }
       }
    return false;
}

Answer №4

Check out this solution utilizing lambda expressions:

var itemDetails = '[alter] saber 1/8 figure unopened';
var trackingList = ['alter saber', 'magic', 'sword art'];
var trackingList2 = ['alter was', 'magic', 'sword art'];

if(trackingList.map(str => str.split(" ")).filter(arrtemp => arrtemp.filter(strin => itemDetails.indexOf(strin) > -1).length == arrtemp.length).length > 0) {
    console.debug("true");
} else {
    console.debug("false")
}

if(trackingList2.map(str => str.split(" ")).filter(arrtemp => arrtemp.filter(strin => itemDetails.indexOf(strin) > -1).length == arrtemp.length).length > 0) {
    console.debug("true");
} else {
    console.debug("false")
}

https://jsfiddle.net/wrz1m0b5/

This method only functions correctly when words are in the precise order.

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

Guide to traversing a JSON Array using PHP and showcasing it in an HTML Table

I'm struggling to parse a JSON Array Response in PHP and display the values in an HTML Table. I have limited experience with PHP-JSON and need some guidance on how to achieve this. $curl_response = curl_exec($curl); echo $curl_response . PHP_EOL; JSO ...

Access specific data within a JSON array in PHP without the need for a foreach loop

Lately, I've been facing some challenges when it comes to decoding and interpreting the prices for specific items in the bitskins api. For instance, the OPSKINS API provides a straightforward output: {"status":1,"time":1477116462,"response":{"AK-47 ...

Encountering an unexpected token in Javascript when using conditionals

I am currently attempting to integrate a JavaScript condition within a listed order, containing two radio buttons that need to be checked in order to progress to the following list based on the selection. <li data-input-trigger> <label class="fs- ...

Struggling to generate a div using my JS/jQuery code

Currently working on a post-it web application to improve my skills in JavaScript and jQuery. I've encountered a few errors that have me stumped. Although I'm new to StackOverflow, I often use it as a helpful resource. You can find the code here ...

What is the best way to merge angularjs modules?

In my angularjs application using the codeigniter PHP framework, I have implemented 3 modules - cars.js for car details, cellphones.js for cellphone details, and home.js for home details. Each module caters to a different client's needs. I am trying ...

Steps for integrating WebRTC recording functionality with a Node.js server

Looking to develop a user-friendly video blogging solution that utilizes WebRTC technology for direct recording of video/audio within the browser, similar to Youtube's My_Webcam. The backend should be powered by Node.js. While exploring various Node. ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

Iterate using jQuery through all child div elements

<div id="SelectedSection" class="selected"> <div class="sec_ch" name="7"> <div class="sec_ch" name="8"> <div class="sec_ch" name="9"> <div class="sec_ch" name="11"> <div class="clear"> </div> </di ...

Could you display the picture prior to the function commencing?

This is the image that needs to be loaded before the loop begins. <div id="attendenceGridDivLoader" style="display:none"> <img src="<?php echo base_url() . 'images/loader.gif'; ?>" /> </div> <select onchange=checkAll ...

Utilizing Angular JS to parse JSON data and showcase it in various tables

Just diving into Angular JS and looking for some guidance. Can someone show me how to parse and showcase JSON Data in separate tables using Angular JS? [ { "id": 0, "isActive": false, "balance": 1025.00, "picture": "htt ...

Trigger a random tune when hovering the mouse

I need help figuring out how to make a fixed image on my page trigger a random sound track when hovered over. The sound could be one of five different tracks. Here is the HTML for my image: <img src="images/Airplane.png" class="Airplane-photo"> Bel ...

Instructions for setting a default value for ng-options when dealing with nested JSON data in AngularJS

I need help setting a default value for my ng-options using ng-init and ng-model with dependent dropdowns. Here is an example of my code: <select id="country" ng-model="statessource" ng-disabled="!type2" ng-options="country for (country, states) in c ...

Creating a CSS selector element with an index is a useful skill to have when

Currently, I am in the process of developing a test application using Selenium that relies on CSS Selectors or XPath strings. One specific challenge I encountered was testing menu items that only appear upon hovering. When utilizing "Inspect Element" in bo ...

Determine if a JSON object is void

Using jQuery, I am checking whether the object returned from an AJAX call is empty or not. In the first example, the AJAX call is successful and returns some data. console.log("obj before JSON parse:", response); var test = $.isEmptyObject(response); con ...

The function of the 'Class' attribute is not functioning properly

I am currently working on a search field with a drop-down menu that determines the type of data being searched. This, in turn, dictates the input type for the search field. For example, if I am searching by "name" or "ID number", the input type is set to t ...

Enhance the code for updating the content within a div element

I recently discovered that utilizing jQuery allows for updating the content within a div. My goal now is to enhance this script so the content remains consistent, even while loading or not. Take a look at my current code: function changeContent () { va ...

New properties are not being successfully added to Passport Profiles

I am currently utilizing Passport OAuth2.0 with Google as my provider and encountering an unusual syntax issue. The structure of my authentication setup is as follows: passport.use(new GoogleStrategy({ clientID: GOOGLE_CLIENT_ID, clientSecret: GO ...

Issue with jQuery: Function not triggered by value selection in dynamically created select boxes

I am in need of some assistance with my code that dynamically generates select drop down menus. I want each menu to trigger a different function when an option is selected using the "onchange" event, but I am struggling to implement this feature. Any hel ...

Launch the jQuery Fancybox on a separate webpage

I am facing an issue where I have a link in my index.html page and I need it to open a div located in another page named index2.html, but for some reason, it is not working. This is the code I currently have: Link in index.html <a href="#modal" id="o ...

The Art of Capturing Sound: Unleashing

Currently, I am attempting to capture video via html5 .getUserMedia and play it back without needing to upload it to a server. Despite following numerous tutorials, I have only been successful on Chrome by utilizing canvas to draw the webp image and then c ...