I have an array with strings: const fruits = ['Apple', 'Banana', 'Orange']
I am trying to write a function that returns true or false depending on if a string starts with any string in the array, which would be true for example 'Applepie'
or 'Bananabread'
.
I found startsWith()
and some()
, and combining them is sort of what I am after.
How would I do this?
Advertisement
Answer
You’d call some
on the array and return the result of theString.startsWith(theArrayEntryForEachLoopIteration)
, like this:
const theString = "Applepie"; const result = fruits.some(fruit => theString.startsWith(fruit));
result
will be true
if there was a match (your callback returned a truthy value), false
if there wasn’t (your callback never returned a truthy value). some
will also stop looking the first time your callback returns a truthy value, since there’s no point in looking further.
Live Example:
const fruits = ['Apple', 'Banana', 'Orange']; // Example where it's there: const theString = "Applepie"; const result = fruits.some(fruit => theString.startsWith(fruit)); console.log(result); // Example where it isn't const theString2 = "Toffeepie"; const result2 = fruits.some(fruit => theString2.startsWith(fruit)); console.log(result2);
MDN has good reference and tutorial content: some
, startsWith
.