use lodash to find substring from array of strings

前端 未结 7 2548
清歌不尽
清歌不尽 2021-02-14 05:03

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 hat         


        
7条回答
  •  时光取名叫无心
    2021-02-14 05:22

    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'));
    

提交回复
热议问题