How do I mix underscore functions to use a custom comparison algorithm for _.contains()?

StackOverflow https://stackoverflow.com/questions/23259424

  •  08-07-2023
  •  | 
  •  

Pregunta

Ideally, I want to pass a custom comparison function to _.contains() as a third argument, but it only accepts a collection and a value.

Code

I want to do this:

_.contains(['apples', 'oranges'], 'applesss', function (element, value) {
  return new RegExp(element).test(value);
});

... but I can't, so what's the next best thing?

¿Fue útil?

Solución

It sounds like you're looking for _.some, which returns true if the test passes for at least one element in the array:

_.some(['apples', 'oranges'], function (element) {
  return new RegExp(element).test('applesss');
});

You can easily wrap it in your own function:

function test_regexes(arr, value) {
  return _.some(arr, function (element) {
    return new RegExp(element).test(value);
  });
}

test_regexes(['apples', 'oranges'], 'applesss');
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top