Clain Dsilva
Clain Dsilva

Reputation: 1651

How to dynamically check if a string contain more than one substring match?

I am trying to build a search suggest that returns the best match below is my code with 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;
    }

I mentioned in the code comments, I am trying to get best match with string containing all the words in search term.

Upvotes: 3

Views: 1847

Answers (1)

kukkuz
kukkuz

Reputation: 42352

Try this - using Array.prototype.every to check if all the search words are there and them filtering out using Array.prototype.filter

Demo below:

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

function loadSuggest(string, search) {
  var terms = search.split(' ');
  return string.filter(function(element) {
    return terms.every(function(e) {
      return element.toLowerCase().indexOf(e.toLowerCase()) !== -1;
    });
  });
}

console.log(loadSuggest(string, "Canna vega"));

Upvotes: 4

Related Questions