Search code examples
arraysswiftfunctional-programming

Swift: Remove from array of strings any element that contains a string from another array


I have array1 and filter it so that any of its elements that contain any of the strings in array2 are removed:

var array1 = ["first.food", "second.easy.good", "third.long.bad", "4.bad.apple", "cinco.Thank You!"]

let array2 = ["food", "bad"]
          

Desired result: array1 = ["second.easy.good", "cinco.Thank You!"]

I achieve this by looping over array2 and filtering array1,

    for string in array2 {
        array1 = array1.filter { !$0.contains(string) }
    }
    

result: array1 = ["second.easy.good", "cinco.Thank You!"]

But can it be done in one line? And if so would it be more or less efficient?

edit: removing the word "functionally" from the question based on accepted reply by @matt.

(Previous question: But can it be done functionally in one line? And if so would it be more or less efficient?)


Solution

  • functionally in one line ... efficient?

    Efficiency might come from parsing the dot-strings into a Set, and especially from turning the second array into a Set, so that contains is faster; in fact, if they are both sets, you can use intersection, which is insanely efficient.

    This would be worth while particularly if the quantities are large, as the preparation does take a little time.

    // your premise
    let array1 = ["first.food", "second.easy.good", "third.long.bad", "4.bad.apple", "cinco.Thank You!"]
    let array2 = ["food", "bad"]
    
    // preparation
    let parsedArray1 = array1.map {($0, Set($0.split(separator: ".").map(String.init)))}
    let set2 = Set(array2)
    
    // okay, _now_ we can be efficient!
    let result = parsedArray1.filter { $0.1.intersection(set2).isEmpty }.map {$0.0}
    
    // done! proof:
    print(result) // ["second.easy.good", "cinco.Thank You!"]
    

    But that has nothing to do with "functional programming", which is merely a way of talking, not a way of improving efficiency. Nor is the "number of lines" of the slightest relevance to efficiency; a one-liner (like my let result line) is fun to look at, but it has no effect whatever on what goes on behind the scenes.