Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter dictionary with arrays as value

Tags:

swift

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

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

like image 618
Alexey K Avatar asked Jul 18 '16 13:07

Alexey K


2 Answers

If I understand your question, you want the keys of a [String: [Object]] dictionary where each Object has a name property 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 you want the dictionary key where an 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 with flatMap and contains

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

print(filteredKeys)

Solution with a loop

var filteredKeys = [String]()

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

print(filteredKeys)
like image 84
Eric Aya Avatar answered Sep 28 '22 03:09

Eric Aya


Yes, but since you got a Dictionary with an array as value:

dictionary.flatMap({ $0.1.filter({ $0.name == "NameToBeEqual"}) })
like image 22
Diogo Antunes Avatar answered Sep 28 '22 01:09

Diogo Antunes