0

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??

Ros
  • 1
  • Use `.find()` instead of `some()`. `.find()` returns the element that matches the condition, or otherwise `undefined`. (So in your `if`, check if the value returned by `.find()` isn't `undefined`.) – Ivar Apr 02 '22 at 13:48

1 Answers1

2

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);
Luiz Avila
  • 1,143
  • 8
  • 7
  • Good answer but be careful with sentences like `var text = "He appeared there to collect a pineapple and few grapes.` However this is a separate problem. – ShivCK Apr 02 '22 at 14:06