Home > Blockchain >  Filtering Array from contents of another Array
Filtering Array from contents of another Array

Time:10-17

I have 2 arrays both with Strings.

let exclude = ["text 1", "text 2", "APP", "John"]
let array2 = ["this is text 1", "This is text 2", "This App is under development", "John is working on this project", "This is great"]

Im trying to filter any text that is contained in exclude from array2, caseInsensitive. So in this example it should print "This is great"

Instead of using multiple lines for each filter like: let filter = array2.filter{!$0.contains("APP")}

I tried: var filter = array2.filter({exclude.contains($0)}) but it does not filter. Any advice would be greatly appreciated

CodePudding user response:

With "explicit" return and no $0.

let filtered = array2.filter { aString in
    return !exclude.contains(where: { anExcludedString in
        return aString.range(of: anExcludedString, options: .caseInsensitive) != nil
    })
}

Why var filter = array2.filter({exclude.contains($0)}) didn't work?

  • First issue:
    There is no case insensitive check.

  • Second issue:
    You are using contains() on a [String], not a String. So it expect full equality between the two strings. So if array2 was ["APP"], it would have worked.

For instance if you had:

let exclude = ["text 1", "text 2", "APP", "John"]
let array2 = ["this is text 1", "This is text 2", "This App is under development", "John is working on this project", "This is great", "This APP is under development"]
let filtered = array2.filter { aString in
    return !exclude.contains(where: { anExcludedString in
        return aString.contains(anExcludedString)
    })
}

Then "This APP is under development" would have been removed.

Now, going back to the initial answer, the way to check case insentive is to use range(of:options:).

  • Related