简体   繁体   中英

Add values of grouped dictionary elements based on keys swift

I have an array of Offering called "offerings". I have grouped the array as shown below.

let groupedBonds = Dictionary(grouping: data.offerings) { (Offering) -> String in
            return Offering.company
        }

public struct Offering: Codable {
    public let company: String
    public let amount: Int
    public let location: String
}

The keys of the dictionary are the companies -> ["ABCD", "EFGH", "IJKL", "MNOP"]

I want to sum all the amounts of the respective companies. Please help me in achieving this result.

Seems you need to find the sum for all grouped arrays, you can use mapValues for this:

let amounts = groupedBonds.mapValues { $0.reduce(0) { $0 + $1.amount} }

amounts will be a dictionary having the same keys as groupedBonds (the company name in this case), but having as values the result of the transformation closure, which, coincidently or not, computes the sum for every array.

assuming what data.offerings equals to

let offerings = [
    Offering(company: "A", amount: 7, location: "a"),
    Offering(company: "A", amount: 4, location: "a"),
    Offering(company: "B", amount: 2, location: "a"),
    Offering(company: "C", amount: 3, location: "a"),
]

I want to sum all the amounts of the respective companies.

  let sumAmountByComany = offerings.reduce(into: [:]) { (result, offer)  in
         result[offer.company] = (result[offer.company] ?? 0 ) + offer.amount
    }

result

[
 "C": 3,
 "B": 2,
 "A": 11
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM