-1

There are a ton of great questions/ answers related to searching / looping through an Array of Strings and matching a given Substring but I couldn't readily find a concise example that uses Lodash to delete / remove any array element that DOES include the desired search substring.

The best resource I found for searching / matching against an array of strings is this question (several good answers): Use lodash to find substring from array of strings

None of those answers appeared to be readily applicable to immediately removing the item IF it matched (true) against the search / substring.

Is there an easy way to loop through an array of strings and delete items that match using Lodash?

While other options are on the table we would ideally want to use Lodash since we already depend on this for many similar functions.

1 Answer 1

0

So I ended up finding a way to use Lodash's _.remove function to accomplish this 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 item via Array mutation.

References: Lodash _.remove documentation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.