0

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.

1
  • Yeah, I'm trying to filter the dictionary based on search results. I would like to return the results that contains the search term Commented Sep 28, 2022 at 9:43

2 Answers 2

1

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
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for your response. Let me try it out
@ashwyllsolutions I have modified my answer
Thankyou for response Joakim. However, Both the solutions you have provided return dictionary with keys but empty values.
Not for me when testing on your sample using your search term.
Okey let me try once more may be I could be making certain errors
|
0

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

var 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
            }
        }

2 Comments

You can't let declare emojiDictFiltered since it is a variable.
Sorry, it is a copying error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.