I'm learning lodash. Is it possible to use lodash to find a substring in an array of strings?
var myArray = [
'I like oranges and apples',
'I hate banana and grapes',
'I find mango ok',
'another array item about fruit'
]
is it possible to confirm if the word 'oranges' is in my array? I've tried _.includes, _.some, _.indexOf but they all failed as they look at the full string, not a substring
isString() Method. The _. isString() method is used to find whether the given value is a string object or not. It returns True if the given value is a string.
Lodash first and last array elements head functions return the first array element; the _. last function returns the last array element.
orderBy() method is similar to _. sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort.
You can easily construct an iteratee for some() using lodash's higher-order functions. For example:
_.some(myArray, _.unary(_.partialRight(_.includes, 'orange')));
The unary() function ensures that only one argument is passed to the callback. The partialRight() function is used to apply the 'orange'
value as the second argument to includes(). The first argument is supplied with each iteration of some()
.
However, this approach won't work if case sensitivity matters. For example, 'Orange'
will return false. Here's how you can handle case sensitivity:
_.some(myArray, _.method('match', /Orange/i));
The method() function creates a function that will call the given method of the first argument passed to it. Here, we're matching against a case-insensitive regular expression.
Or, if case-sensitivity doesn't matter and you simply prefer the method()
approach, this works as well for ES2015:
_.some(myArray, _.method('includes', 'orange'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With