1

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")]
3
  • Do you look for specific transformation logic or you just want to make each element trunk into an array of one element? Commented May 23, 2022 at 2:13
  • 2
    You can simply do this: let output = Array(Dictionary(grouping: input){$0.count}.values) Commented May 23, 2022 at 2:38
  • Purchase(count: 3, food: "soda") is not contained in input. Commented May 23, 2022 at 3:57

1 Answer 1

1

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

Dictionary(grouping: input, by: \.count).map(\.value)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.