I know this been answered multiple times but I can't seem to find an answer based on my situation. I have two arrays:
words ['word1', 'word2', 'word3']
texts [
{name: 'blah', description: 'word4'},
{name: 'blah2', description: 'word1'},
{name: 'blah3', description: 'word5'}
]
I am trying to filter the two arrays and return true if there is a match
I have seen several examples of simple arrays of numbers but that does not apply here.
You can use filter and includes together to know which word is present in the object
You can iterate
texts
usingArray.prototype.some()
and check for matches inwords
usingArray.prototype.includes()
. This is O(nm) time complexity if the length ofwords
andtexts
aren
andm
respectively.Another solution that's O(n + m) time complexity uses
Set.prototype.has()
instead, but this approach will likely be negligibly faster or even a little slower ifwords
is a small array, so only use this ifwords
is extremely large.Update
To address your issue regarding case-sensitivity, I recommend a somewhat different approach. Since both arrays will contain words with mixed casing, convert one of the arrays to regular expressions and test each regular expression against all the words in the other array with the case-insensitive flag.
If your words contain non-alphanumeric characters as well, I highly suggest you borrow this function to escape your regular expressions properly. If you don't escape them, you could potentially end up with cases like below causing your code to throw errors or provide incorrect results.
I think this will solve your issue: