简体   繁体   中英

Consolidate array data on unique values

In Swift, given a struct containing an int, and a string, is it possible to sum the int, based on the string value (feels like a key, value issue)

given:

struct Structure {
    let number: Int
    let text: String
}

var arrayOfStructs: [Structure] = [
    Structure(number: 3, text: "foo"),
    Structure(number: 5, text: "bar"),
    Structure(number: 7, text: "foo")
    ]

arrayOfStructs.count()==3

output an array where elements 0 and 2 are effectively 'summed' resulting in:


arrayOfStructs[0] == Structure(number:10, text: "foo")
arrayOfStructs[1] == Structure(number:5, text: "bar")
arrayOfStructs.count() == 2 

Here is one way to reduce the array of structs into a new array where each text value occurs once and the number value is the sum for the corresponding text values.

struct Structure{
    let number: Int
    let text: String
}

var arrayOfStructs: [Structure] = [
    Structure(number: 4, text: "A"),
    Structure(number: 2, text: "B"),
    Structure(number: 5, text: "C"),
    Structure(number: 7, text: "A"),
    Structure(number: 3, text: "C"),
    Structure(number: 1, text: "A"),
    Structure(number: 6, text: "C"),
]

let newStructs = arrayOfStructs
                     .reduce(into: [String: Int]()) { $0[$1.text, default: 0] += $1.number }
                     .map { Structure(number: $0.value, text: $0.key) }
print(newStructs)

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