Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Filter a Dictionary with Array as Value

I'm new to Swift programming. For my particular project, I'm trying to filter a dictionary with some user input, and the dictionary's value consists of an array.

Here is some sample code, and what I'm trying to accomplish:

var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]

var filteredDictionary = [String: [String]]()

var searchText = "aberration"

//getting the first letter of string
var firstLetter = searchText[searchText.startIndex]

With this particular searchText, I'm trying to get:

filteredDictionary = ["a": ["aberration"]]

Edit: I want the dictionary to return with the first letter as its key, and the values with what searchText matches up with. Sorry if it I wasn't clear.

Here is some code I have tried, but obviously, I can't get it to work:

filteredDictionary = dictionary.filter{$0.key == firstLetter && for element in $0.value { element.hasPrefix(searchText) }}

Any help would be appreciated. Thanks.

like image 775
Alan Dolan Avatar asked Oct 21 '25 12:10

Alan Dolan


2 Answers

Here's a solution that maps the values based on the search and then filters out the empty results.

var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]
var searchText = "aberration"
let filteredDictionary = dictionary.mapValues { $0.filter { $0.hasPrefix(searchText) } }.filter { !$0.value.isEmpty }
print(filteredDictionary)

Output:

["a": ["aberration"]]

like image 90
rmaddy Avatar answered Oct 23 '25 07:10

rmaddy


let firstLetter = String(searchText[searchText.startIndex])
let filteredDictionary = dictionary
    .reduce(into: [String: [String]]()) { (result, object) in
        if object.key == firstLetter {
            let array = object.value.filter({ $0.hasPrefix(searchText) })
            if array.count > 0 {
                result[object.key] = array
            }
        }
    }

Output:

["a": ["aberration"]]

like image 33
iWheelBuy Avatar answered Oct 23 '25 07:10

iWheelBuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!