You could do something like this:
if ($scope.favoriteItems.some(item => (new RegExp(item.name, 'i')).test(item))) {
// do something
}
Basically, to create a RegExp with a variable, you can new RegExp()
, and give it the expression you want as the first parameter, and any flags as the second.
So, something like:
var name = 'abc';
new RegExp(name, 'i');
turns into:
/abc/i
var name = 'abc';
console.log(new RegExp(name, 'i'));
The Array.prototype.some
function loops through each item in an array and keeps going until one returns true. In this case, we keep looping until one of them matches our regexp (meaning it's in the array) and then we stop.
That said, unless item.name
is going to be something that isn't just a string match, using a regex test is massive overkill and you'd be better off sticking with what you have.