Search code examples
iosmultidimensional-arrayswift4higher-order-functions

How to get grouped array of struct in swift 4?


I have an array of structs in which ingredientId can be same for two or more elements. Code for the same is as below:

struct Cart {
    var bundleId: Int = 0
    var ingredientId: Int = 0
}

var array:[Cart] = []
array.append(Cart(bundleId: 1, ingredientId: 1))
array.append(Cart(bundleId: 2, ingredientId: 2))
array.append(Cart(bundleId: 3, ingredientId: 2))
array.append(Cart(bundleId: 4, ingredientId: 5))
array.append(Cart(bundleId: 5, ingredientId: 5))
array.append(Cart(bundleId: 6, ingredientId: 6))
print(array)

What I am expecting as output is an array with elements grouped according to same ingredientId e.g.

[
   [Cart(bundleId: 1, ingredientId: 1)],
   [Cart(bundleId: 2, ingredientId: 2),Cart(bundleId: 3, ingredientId: 2)],
   [Cart(bundleId: 4, ingredientId: 5),Cart(bundleId: 5, ingredientId: 5)],
   [Cart(bundleId: 6, ingredientId: 6)],
   ............
   .......
]

P.S.: ingredientId's are not fixed and we don't have separate array for them.

How to achieve this using Higher order functions?


Solution

  • You can used the grouped API exposed by the Dictionary to transform your array in to a dictionary of Carts grouped by ingredientId;

    let groupedDictionary = Dictionary(grouping: array) { $0.ingredientId }
    

    If you then need to transform that Dictionary in to an Array;

    let twoDimensionalArray = groupedDictionary.map { $0.value }