use lodash to find substring from array of strings

前端 未结 7 2500
清歌不尽
清歌不尽 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:19

    The best way is to define a function to check the inclusion of a substring.

    var contains = _.curry(function (substring, source) {
        return source.indexOf(substring) !== -1;
    });
    

    I use _.curry here to get a curried function, which can be partially applied then.

    _.some(myArray, contains('item'));
    

    You can also find a substring in a joined string.

    contains('item', _.join(myArray))
    

    UPD:

    I have not noticed that lodash already has a function to find value in a collection.

    The function _.includes is quite the same to what I defined above. However, as everything in lodash, it uses the different order for arguments. In my example, I put a source as the latest argument for a curried function which makes my function useful for point-free style programming when lodash waits for the source as a first argument of the same function.

    Check the Brian Lonsdorf's talk on this matter https://www.youtube.com/watch?v=m3svKOdZijA

    Also take a chance to look into ramda. This library provides a better way for practical functional programming in JavaScript.

提交回复
热议问题