You can iterate texts
using Array.prototype.some()
and check for matches in words
using Array.prototype.includes()
. This is O(nm) time complexity if the length of words
and texts
are n
and m
respectively.
const words = ['word1', 'word2', 'word3']
const texts = [
{name: 'blah', description: 'word4'},
{name: 'blah2', description: 'word1'},
{name: 'blah3', description: 'word5'}
]
console.log(
texts.some(
({ description }) => words.includes(description)
)
)
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 if words
is a small array, so only use this if words
is extremely large.
const words = new Set(['word1', 'word2', 'word3'])
const texts = [
{name: 'blah', description: 'word4'},
{name: 'blah2', description: 'word1'},
{name: 'blah3', description: 'word5'}
]
console.log(
texts.some(
({ description }) => words.has(description)
)
)
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.
const words = ['word1', 'WORD2', 'Word3']
const texts = [
{name: 'blah', description: 'Word4'},
{name: 'blah2', description: 'Word1'},
{name: 'blah3', description: 'Word5'}
]
console.log(
texts.some(({ description }) => {
const regexp = new RegExp(description, 'i')
return words.some(word => regexp.test(word))
})
)
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.
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
const words = ['?WORD1', 'word2', 'Word3']
const texts = [
{name: 'blah', description: 'Word4'},
{name: 'blah2', description: '?Word1'},
{name: 'blah3', description: 'Word5'}
]
console.log(
texts.some(({ description }) => {
const regexp = new RegExp(escapeRegExp(description), 'i')
return words.some(word => regexp.test(word))
})
)