1
const arr = ['be-', 'fe-', 'automated'];

const str = 'fe-cheese';
const oi = arr.includes(str) ? 'cheese' : 'meat';

console.log(oi);

I have an array of partial matches and I want to check to see if the string contains any of the partials in the arr.

The above returns meat when it should match fe- and return cheese

0

1 Answer 1

6

You can use Array.some. It will iterate over an array and return true if any of the iterations return true. Note: This has the added benefit of short-circuit execution, meaning that once it reaches the first iteration that returns true, it does not continue the rest of the iterations, as they are unnecessary.

const arr = ['be-', 'fe-', 'automated'];

const str = 'fe-cheese';
const oi = arr.some(a => str.indexOf(a) > -1) ? 'cheese' : 'meat';

console.log(oi);

Verify that at least one of the elements is present (indexOf) in the provided string.

Sign up to request clarification or add additional context in comments.

3 Comments

why not just use .indexOf() for full browser support? Also, shouldn't you be checking with .toLowerCase()?
You can use indexOf - I originally had that, but changed it to includes based on comments. You can use toLowerCase as well, if you want to ignore case sensitivity. OP didnt specify they wanted to ignore case, so I didnt.
@tymeJV True, I guess I was assuming case insensitivity because of partial matching, but you're right - I don't know if that's a safe assumption to make unless we get more details from the OP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.