use lodash to find substring from array of strings

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

    You can do this using lodash, but it's also very doable using native javascript methods:

    function stringArrayContains(array, str) {
      function contains(el) {
        return (el.indexOf(str) !== -1) ? true : false;
      }
    
      return array.some(contains);
    }
    

    Testing the above function:

    var a = ['hello', 'there'];
    var b = ['see', 'ya', 'later'];
    
    stringArrayContains(a, 'ell') // true
    stringArrayContains(a, 'what') // false
    stringArrayContains(b, 'later') // true
    stringArrayContains(b, 'hello') // false
    

    Array.prototype.some applies a function you define to every element of an array. This function (named contains in our case) must return true or false. While iterating through the array elements, if any of the elements returns true, the some method returns true.

    Personally, I think in general that if you can use native JS methods for simple functions, it's preferable to loading an library just to do the same thing. Lodash absolutely does have performance benefits, but they aren't necessarily realized unless you're processing large amounts of data. Just my two cents.

    Cheers!

    0 讨论(0)
提交回复
热议问题