Is it possible to check dynamically if a string contains multiple substring matches?

Currently, I am in the process of developing a search suggest feature that will provide the best match based on certain criteria. Below is the code snippet along with my explanatory comments.


    /*
    string = {"Canna Terra PLUS 50 Litres", "Canna Vega Tent", "Canna Bio Vega", "Super Canna 50 max" }
    search = "Canna Vega"  this can be dynamic ranging up to 4 words search term

    The expected return array would be

    {"Canna Vega Tent", "Canna Bio Vega" }

    */

    function loadSuggest(string,search){

        if( search.length < 3 ){ 
            return; // suggest is loaded only if the search term is more than 3 letter
        }

        var terms = search.split(' '); // split the search term with spaces
        var i;

        for(i = 0; i < string.length; i++){

            /*
            how to dynamically check and return
            the results containing more than one term match ?
            I have tried indexOf() but that fails with dynamic number of words matching
            */

        }
        return resultArray;
    }

Included within the comments of the code are my efforts towards achieving a return result that contains all the terms present in the search query for optimal matching.

Answer №1

Here's a suggestion - utilize Array.prototype.every to verify the presence of all search words and then filter them out using Array.prototype.filter

Check out the demonstration below:

var items = ["Canna Terra PLUS 50 Litres", "Canna Vega Tent","Canna Bio Vega", "Super Canna 50 max"];

function suggestItems(items, search) {
  var terms = search.split(' ');
  return items.filter(function(item) {
    return terms.every(function(term) {
      return item.toLowerCase().indexOf(term.toLowerCase()) !== -1;
    });
  });
}

console.log(suggestItems(items, "Canna vega"));

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

Steps to invoke a function in a PHP file from an external JavaScript file

Can anyone assist me with calling the function below in my PHP file? function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { //alert(el[settings.tokenValue]); return el[ ...

Having trouble fetching values in Node.js after a certain period of time has passed

Whenever the page loads, the sha1 function is supposed to run and it should run after 5 seconds. var crypto = require('crypto'); console.log(sha1()); setTimeout(sha1, 5000); console.log(sha1()); function sha1() { var dt = dateTime.create(); ...

Establishing parameters in a Socket.io chatroom

I am encountering an issue when attempting to store information in the socket room variables. The error message I receive is: UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'host' of undefined This is the snippet of my code: io ...

Adding a marker to Google Maps in React that displays the user's current location

I successfully integrated Google Maps into my website and now I want to add a marker for the user's location. The first file is Map.js, and the second one is MapContainer.js. In MapContainer.js, I have all the necessary data for map rendering, includi ...

The error "localStorage is not defined when using an axios interceptor in NextJS"

Within my root directory, there lies a file named api.js. This particular file is responsible for managing calls to an external API, with a focus on request and response interceptors. One specific use case involves injecting the access_token, leading to th ...

Utilizing HTTP POST method in vanilla JavaScript with AJAX

Having some trouble sending a post request to my PHP file as it keeps saying 'undefined index'. Here is my JavaScript code: document.getElementById("btn1").addEventListener('click', xh ); function xh(){ xhr = new XMLHttp ...

Integrate PHP include files into a website without allowing direct access, then dynamically load them using jQuery AJAX

I am utilizing jQuery AJAX to load the content of about.php page into my index.php section in this manner: $('.nav a[href="#about"]').on('click', function() { $('main').load('../../layout/about.php'); }); The iss ...

Creating a multitude of cubes by iterating through the pixel color data of getImageData in Three.js

Using a simple 3x3.png file to extract color/opacity data from, where each of the 9 pixels represents a different color/opacity level. The .png is supposed to be loaded onto an off-screen canvas, following which the 9 cubes are drawn in a 3x3 grid pattern ...

Retrieve SQL data and store it in a JavaScript variable

Need assistance with fetching data from SQL and storing it in a JavaScript variable. I have already connected PHPMyAdmin to my website. I am attempting to retrieve two variables (date) from my SQL table. JAVASCRIPT: var countdown_48 = new Date; countdow ...

Why must the sidebar be displayed horizontally on the smartphone screen?

I've been struggling to make the sidebar menu on my smartphone display horizontally with icons at the top and text at the bottom. I've tried using flex and other methods, but it still doesn't work sideways. Am I missing something? const s ...

Scroll the div that is dynamically filled without affecting the scrolling of the main page

My current struggle involves using iScroll in my web project. The goal is to populate a list with articles and slide in a div over the list to display the selected article. While the basic functionality is in place, I face an issue where scrolling through ...

Having trouble determining the dimensions of a newly added element

I am using jQuery to dynamically add an image but I am unable to retrieve its dimensions (width and height). Below is the snippet of code from my HTML file: <input type="checkbox" id="RocketElement" data-id="1"> And here is the JavaScript/jQuery c ...

Is there a way to personalize the appearance of Static File in nextjs?

Is there a way to customize the display of static files, particularly images? For instance, when accessing a static file on a website like this: Currently, it just shows a basic img element. Is it possible to dynamically add additional elements to that d ...

Configuring the Port for NodeJS Express App on Heroku

Currently, I am in the process of hosting my website on Heroku and configuring everything to ensure my app is up and running smoothly. However, each time I attempt to submit the form, undefined errors occur. For more details on the Undefined Errors and Co ...

Ensuring the cumulative size of a map (the combined length of all keys and values) remains under the specified limit

From a specific data source, I am receiving a large number of records that need to be sent to our database. Here is my approach: I store these records in a ConcurrentHashMap where the key is an Integer and the value is a ConcurrentLinkedQueue. Multiple t ...

Checking authentication globally using Vue.js

In the main blade file, I have the following code snippet: <script> window.App = {!! json_encode([ 'csrfToken' => csrf_token(), 'user' => Auth::user(), 'signedIn' => Auth::check() ...

Submitting content to numerous webpages

I'm looking to submit form data on multiple pages, while keeping the main action as "". After clicking, I want the page to refresh but also send the POST data to another .php file. This is necessary because the other .php file generates a graph that ...

Steps for deleting a game objectWould you like to learn how to

What is the process of creating an object that can eliminate itself automatically? var item = []; function selfDestruct() { this.destroy = () => { this = false; } } function initialization() { item[0] = new SelfDestruct(); item[0].destroy( ...

Creating an efficient login system for my website - where do I start?

I've recently started diving into the world of web development, starting with HTML, CSS, and a bit of JavaScript. However, I've hit a roadblock - while I can perform basic styling, I'm struggling to make my projects interactive. My main que ...

By utilizing the window.history.back() function, it takes me four clicks to navigate back one page

I find it peculiar that my back button is using the JS method window.history.back() to return to the previous page. However, I have noticed a strange behavior with this button. When I click on it before the entire document loads, it functions as expected a ...