Home > Mobile >  Swift How to break an array of objects into an array of arrays?
Swift How to break an array of objects into an array of arrays?

Time:05-23

I have an array of purchase objects [Purchase] defined as:

struct Purchase {
    let count: Int
    let food: String
}

How can I get turn this array of purchases into an array of arrays of purchases with the same count (Int)?

For example:

let input: [Purchase(count: 2, food: "popcorn"), Purchase(count: 3, food: "popcorn"),  Purchase(count: 2, food: "soda"),
            Purchase(count: 2, food: "popcorn"), Purchase(count: 2, food: "soda")]

output: [[Purchase]] = [[Purchase(count: 2, food: "popcorn"), Purchase(count: 2, food: "soda"),
          Purchase(count: 2, food: "popcorn"), Purchase(count: 2, food: "soda")], [Purchase(count: 3, food: "soda")]

CodePudding user response:

The answer is in the comments but it can look a little cleaner.

Dictionary(grouping: input, by: \.count).map(\.value)
  • Related