use lodash to find substring from array of strings

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

    I ran into this Question / Answer thread while trying to figure out how to match a substring against each String in an Array and REMOVE any array item that contains that substring.

    While the above answers put me on track, and while this doesn't specifically answer the original question, this thread DOES appear first in the google search when you are trying to figure out how to accomplish the above removal of an array item so I figured I would post an answer here.

    I ended up finding a way to use Lodash's _.remove function to remove matching array strings as follows:

            // The String (SubString) we want to match against array (for dropping purposes)
            var searchSubString = "whatever" 
    
            // Remove all array items that contain the text "whatever"
            _.remove(my_array, function(searchSubString) {
                  return n.indexOf(searchSubString) !== -1;
                });
    

    Basically indexOf is matching against the position of the substring within the string, if the substring is not found it will return -1, when indexOf returns a number other than -1 (the number is the SubString position in number of characters within the Array string).

    Lodash removes that Array item via array mutation and the newly modified array can be accessed by the same name.

提交回复
热议问题