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
findonberriesKeywordsto find the first match - Using
someto find a match for a single value ofberriesKeywordsamongingredients - Using
includesto have a partial string match between a single value ofberriesKeywordsand 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.
