Filter dictionary with arrays as value

I have a dictionary [String: [Object]]. Each object has.name

Is it possible to use a dictionary .filterin a dictionary to return a dictionary only with keys that contain a filtered value?

+4
source share
2 answers

If I understand your question, you need dictionary keys[String: [Object]] , where everyone Objecthas a property name, and this property has a given value.

struct Obj {
    let name: String
}

let o1 = Obj(name: "one")
let o2 = Obj(name: "two")
let o3 = Obj(name: "three")

let dict = ["a": [o1, o2], "b": [o3]]

Now let's say that you need a dictionary key, where the object has “two” for its name:

Solution with filter

let filteredKeys = dict.filter { (key, value) in value.contains({ $0.name == "two" }) }.map { $0.0 }

print(filteredKeys)

Solution flatMapandcontains

let filteredKeys = dict.flatMap { (str, arr) -> String? in
    if arr.contains({ $0.name == "two" }) {
        return str
    }
    return nil
}

print(filteredKeys)

Loop solution

var filteredKeys = [String]()

for (key, value) in dict {
    if value.contains({ $0.name == "two" }) {
        filteredKeys.append(key)
    }
}

print(filteredKeys)
+6
source

Yes, but since you received a dictionary with an array as a value:

dictionary.flatMap({ $0.1.filter({ $0.name == "NameToBeEqual"}) })
+2

Source: https://habr.com/ru/post/1648263/


All Articles