Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use lodash to find substring from array of strings

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

like image 889
John Paul Vaughan Avatar asked Feb 24 '16 23:02

John Paul Vaughan


People also ask

How do you check for Lodash strings?

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.

What does _ do in Lodash?

Lodash first and last array elements head functions return the first array element; the _. last function returns the last array element.

How do you use orderBy Lodash?

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.


1 Answers

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'));
like image 167
Adam Boduch Avatar answered Sep 18 '22 13:09

Adam Boduch