Search code examples
javascriptecmascript-6ecmascript-2016

Check if string contains any keywords that exists in array


I am trying to filter some content based on which keyword exists in an array, but not sure how to do that, tried using includes, indexof , and search functions, but it didn't work in my case.

My first attempt:

const filters = ['movie', 'food']
contents
 .filter( content => filters.includes(content.name))

the problem is that content.name is a string with multiple words eg "watch your favourite movie", "vote for your favourite food", etc. and I want to check if a string includes one of the keywords in filters variable. Currently includes() returns false because it's trying to match the exact string.


Solution

  • You need to check each word in filters against each content.name. You can do that with .some() which will return true (and halt the search early) when a match is found.

    const filters = ['movie', 'food']
    const result = contents.filter(content => 
      filters.some(s => content.name.includes(s))
    )
    

    Note that .includes() will match subsections of words. You need to establish word boundaries, perhaps with a regex, to get a whole word match.

    You can do this by creating an array of regexes instead of strings, and using the .test() method of the regex.

    const filters = [/\bmovie\b/, /\bfood\b/]
    const result = contents.filter(content => 
      filters.some(re => re.test(content.name))
    )
    

    Add the i modifier to each regex if it should be a case insensitive match.

    Or instead of an array of regex, you can use a single regex.

    const filters = /\b(?:movie|food)\b/
    const result = contents.filter(content => filters.test(content.name))