Hi, guys I have a array like this:
[ [icon: "A", amount: 11], [icon: "B", amount: 10], [icon: "A", amount: 15], [icon: "B", amount: 13], [icon: "C", amount: 5] ]
Right now I only can show them in list one by one like:
icon: "A", amount: 11
icon: "B", amount: 10
icon: "A", amount: 15
icon: "B", amount: 13
icon: "C", amount: 5
How can i show them in a List like:
icon: "A", amount: 26
icon: "B", amount: 23
icon: "C", amount: 5
I appreciate it for any help and suggestions !
How are icon and amount defined ?
I tested this:
typealias Element = [String: Any]
// I guessed a definition of icon and amount
let icon = "icon"
let amount = "amount"
let myDict : [Element] = [ [icon: "A", amount: 11], [icon: "B", amount: 10], [icon: "A", amount: 15], [icon: "B", amount: 13], [icon: "C", amount: 5] ]
To calculate the sum for "A", we first filter the dictionary for icon "A"
let myDictA = myDict.filter() { $0[icon] as! String == "A" }
Then we can compute the sum of amount with reduce (note this is not yet totally robust if item[amount] was nil…
let totalA = myDictA.reduce(0) { sum, item in sum + (item[amount] as! Int)}
So we can write it in a single line
let totalA = myDict.filter() { $0[icon] as! String == "A" }.reduce(0) { sum, item in sum + (item[amount] as! Int)}
To compute for all icons, we shall first extract the icons ("A", "B", …) in an array icons.
var icons : [String] = []
for elem in myDict {
if elem[icon] != nil && !icons.contains(elem[icon] as! String) { icons.append(elem[icon] as! String) }
}
Note that we test for nil, hence avoiding a crash.
To get the sum for each icon, we shall make the same computation that we did as example for totalA, looping through the icons we have found. And we put the result in the correct key in a dictionary.
var sums : [String] = []
for ic in icons {
sums[ic] = myDict.filter() { $0[icon] as! String == ic }.reduce(0) { sum, item in sum + (item[amount] as! Int)}
}
print(sums)
We get the following:
["C": 5, "A": 26, "B": 23]
If you want it ordered, you could write:
let sortedSums = sums.map() { ($0.key, $0.value)}.sorted() { $0.0 < $1.0 }
print(sortedSums)
and get:
[("A", 26), ("B", 23), ("C", 5)]