Reputation: 4417
I was looking for my answer and found this: multiple conditions for JavaScript .includes() method
but, this solution does either one or all of the words from the list:
//checks for one
const multiSearchOr = (text, searchWords) => (
searchWords.some((el) => {
return text.match(new RegExp(el,"i"))
})
)
//checks for all
const multiSearchAnd = (text, searchWords) => (
searchWords.every((el) => {
return text.match(new RegExp(el,"i"))
})
)
These work, but i need to be able to match on two or more words in my passed in list. Like the following:
let name = "jaso bour 2";
let spl = name.split(' ');
let passed = multiSearchAnd("my name is jason bourne the fourth on the fifth", spl);
console.log(passed);
The variable passed in the above scenario is false but i want it to be true since the strings "jaso" and "bour" are in the searched string.
How do i alter the multiSearchAnd function so it will return true if two or more words are found from the passed in list and not just all of them? Thanks
Upvotes: 0
Views: 495
Reputation: 11080
The two functions from the solution you found use Array#some()
and Array#every()
. These array helpers can only do two things: either any element in the array satisfies the condition (so, matching at least 1) or every element satisfies the condition. You want a specific number, so you can't really easily use these helper functions. However, you can do this yourself with a simple loop:
const multiSearchAtLeastN = (text, searchWords, minimumMatches) => {
let matches = 0;
for (let word of searchWords) {
if (text.includes(word) && ++matches >= minimumMatches) return true;
}
return false;
};
//demonstration
let name = "jaso bour 2";
let spl = name.split(' ');
let passed = multiSearchAtLeastN("my name is jason bourne the fourth on the fifth", spl, 2);
console.log(passed);
This has the benefit of returning the result as soon as one is known, as opposed to other possible solutions involving .filter()
which would have to iterate the entire array first with no early-exit.
If you value concise code, you can also make this work with a clever usage of Array#some()
with early exit:
const multiSearchAtLeastN = (text, searchWords, minimumMatches) => (
searchWords.some(word => text.includes(word) && --minimumMatches <= 0)
);
//demonstration
let name = "jaso bour 2";
let spl = name.split(' ');
let passed = multiSearchAtLeastN("my name is jason bourne the fourth on the fifth", spl, 2);
console.log(passed);
Upvotes: 2
Reputation: 5055
You can use a .filter()
to build an Array of your matching strings, and then check against the length of this Array
let name = "jaso bour 2";
let spl = name.split(' ');
let passed = multiSearchAnd("my name is jason bourne the fourth on the fifth", spl);
console.log(passed);
function multiSearchAnd(input, matchArr) {
return matchArr.filter(x => input.includes(x)).length >= 2;
}
Upvotes: 2