How to group array of objects in swift?

Ronak Patel
1 min readNov 27, 2024

--

  • Dictionary(grouping:by:): Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.

Parameters:

  • valuesA sequence of values to group into a dictionary.
  • keyForValueA closure that returns a key for each element in values.

Discussion

The arrays in the “values” position of the new dictionary each contain at least one element, with the elements in the same order as the source sequence.

let’s understand Grouping by an example,
suppose we have an array of item,

foodItems = [
FoodItem(id: 1, type: "fruit", name: "Apple"),
FoodItem(id: 2, type: "vegetable", name: "Carrot"),
FoodItem(id: 3, type: "fruit", name: "Banana"),
FoodItem(id: 4, type: "vegetable", name: "Broccoli")
]

And here If you want to group items by their food type, you can use Dictionary(grouping:by:)

let groupedItems = Dictionary(grouping: foodItems, by: { $0.type })
print(groupedItems)

Output:

The result will be a dictionary where the keys are the type values, and the values are arrays of Items

[
"fruit": [
FoodItem(id: 1, type: "fruit", name: "Apple"),
FoodItem(id: 3, type: "fruit", name: "Banana")
],
"vegetable": [
FoodItem(id: 2, type: "vegetable", name: "Carrot"),
FoodItem(id: 4, type: "vegetable", name: "Broccoli")
]
]

Thanks!!!!!!!!!!!!!!!!!!

--

--

No responses yet