Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Elements in Dictionary by The Last Character of The Keys [iOS Swift 5]

I have a dictionary that I want to group by the last character of the keys. This is the dictionary:

var displayValues = ["volume_1": 1, "price_2": 6, "price_1": 2, "stock_1": 3, "volume_2": 5, "stock_2": 7]

This is the code that I used in order to group them

let groupValues = Dictionary(grouping: displayValues) { $0.key.last! }
print(groupValues)

This is the result of this code

["2": [(key: "price_2", value: 6), (key: "volume_2", value: 5), (key: "stock_2", value: 7)], "1": [(key: "volume_1", value: 1), (key: "price_1", value: 2), (key: "stock_1", value: 3)]]

The grouping is correct, however, how do I remove the words key and value from the dictionary so that it will display the following?

[
  "2": ["price_2": 6, "volume_2" : 5, "stock_2": 7], 
  "1": ["volume_1": 1, "price_1": 2, "stock_1": 3]
]
like image 377
TSM Avatar asked Mar 03 '23 20:03

TSM


1 Answers

You are almost there !!

now You have key as you wanted and value as array of tuple

You can convert array of tuple into dictionary with new reduce(into:)

full code would be

    var displayValues = ["volume_1": 1, "price_2": 6, "price_1": 2, "stock_1": 3, "volume_2": 5, "stock_2": 7];
    let dict = Dictionary(grouping: displayValues) { $0.key.suffix(1)}
    let final = dict. mapValues { value  in
        return value.reduce(into: [:]) { $0[$1.key] = $1.value }
    }
    print(final)

Output :

["2": ["price_2": 6, "volume_2": 5, "stock_2": 7], "1": ["price_1": 2, "stock_1": 3, "volume_1": 1]]

like image 74
Prashant Tukadiya Avatar answered Mar 05 '23 15:03

Prashant Tukadiya