I'm trying to write a cloud function. I have a const array of keywords, such as:
const berriesKeywords = [
"berries",
"berry",
"cherries",
"grapes",
"kumquats",
"currant"
]
The cloud function accepts a list of ingredients data.ingredients
that, e.g., might contain:
[
"tomatoes",
"romain lettuce",
"concord grapes",
"tempeh"
"kumquats",
"currant"
]
I want to traverse each berriesKeywords
until I find a contains match in data.ingredients
. In the example above, we should stop at grapes
, because of concord grapes
. So basically I only care if there was one match. What's the best way of doing this?
CodePudding user response:
You can try this approach
- Using
find
onberriesKeywords
to find the first match - Using
some
to find a match for a single value ofberriesKeywords
amongingredients
- Using
includes
to have a partial string match between a single value ofberriesKeywords
and a single value ofingredients
const berriesKeywords = [
"berries",
"berry",
"cherries",
"grapes",
"kumquats",
"currant"
]
const ingredients = [
"tomatoes",
"romain lettuce",
"concord grapes",
"tempeh",
"kumquats",
"currant"
]
const result = berriesKeywords.find(berriesKeyword => ingredients.some(ingredient => ingredient.includes(berriesKeyword)))
console.log(result)
Here is the playground if you cannot run it here
By the way, these functions are from Javascript but have no differences in Typescript, so you can use them without any problems.