I have an array of strings. I want to check if any of those strings is present in one sentence, so I used some() and includes(), and got a boolean telling me if any of the strings are present. So far so good.
Now, I need to know which of those strings is the one included in the sentence.
Here's my code:
var fruits = [
"apple",
"pear",
"orange",
"banana",
"grapes",
];
var text = "I want to eat a banana";
if (fruits.some(v => text.includes(v))) {
console.log("One of the fruits is in the sentence!");
}
I would need to get the value of that 'v', but I can't find a way to do it. Any ideas??
You could use find if its just one occurrence or filter if you want multiples:
var fruits = [
"apple",
"pear",
"orange",
"banana",
"grapes",
];
var text = "I want to eat a banana and an orange";
var foundFind = fruits.find(fruit => text.includes(fruit))
console.log("foundFind", foundFind);
var foundFilter = fruits.filter(fruit => text.includes(fruit))
console.log("foundFilter", foundFilter);