Home > Software engineering >  Filter dictionary with value as array of an arrays in swift programmatically
Filter dictionary with value as array of an arrays in swift programmatically

Time:09-28

I have the following dictionary and I would like to filter as follows

var emojiDict = [String: [[String]]]()
emojiDict = ["key one":[["item name 1", "item photo 1"],["item name 2", "item photo 2"], ["item name 3", "item photo 3"]],

"key two":[["item name 1", "item photo 1"],["item name 2", "item photo 2"], ["item name 3", "item photo 3"]],

"key three":[["item name 4", "item photo 1"],["item name 2", "item photo 2"], ["item name 3", "item photo 3"]]] 

I would like to filter the above dictionary with search term item name 1 and return the following results

emojiDict = ["key one":[["item name 1", "item photo 1"]],

"key two":[["item name 1", "item photo 1"]]] 

I tried below solution but it didn't work

let searchText = "item name 1"

let emojiDictFiltered = emojiDict.mapValues { $0.filter { $0.hasPrefix(searchText) } }.filter { !$0.value.isEmpty }
  

I kindly request for your assistance.

CodePudding user response:

Here is a solution using reduce(into:) to filter out the matches

let filtered = emojiDict.reduce(into: [String: [[String]]]()) {
    let result = $1.value.filter { $0.contains(searchTerm)}
    if result.isEmpty == false {
        $0[$1.key] = result
    }
}

CodePudding user response:

Finally I have managed to solve the issue I'm facing

let emojiDictFiltered = [String: [[String]]]()

for (key, value) in emojiDict {
            let result = value.filter { (dataArray:[String]) -> Bool in
                return dataArray.filter({ (string) -> Bool in
                    return string.contains(searchText!)
                }).count > 0
            }
            
            if result.isEmpty == false {
                emojiDictFiltered[key] = result
            }
        }
  • Related