Ungroup and GroupBy functions in Power Apps

In Power Apps, collections are used to store and manage sets of data from various sources such as SharePoint, Dataverse,… in your app. The GroupBy and Ungroup functions are used to group or ungroup data within a collection.

In this post we will learn how to use these functions with a sample collection in our apps. These functions are very useful when you want to create nested galleries in Power Apps.

Assume we have the following collection called MyCollection:

FirstNameLastNameAge
JohnSmith25
JaneDoe30
JohnDoe40
BobSmith35
ClearCollect(MyCollection,
    {FirstName:"John", LastName:"Smith", Age:25},
    {FirstName:"Jane", LastName:"Doe", Age:30},
    {FirstName:"John", LastName:"Doe", Age:40},
    {FirstName:"Bob", LastName:"Smith", Age:35}
)

To group the data in MyCollection by the LastName column, we can use the GroupBy function:

ClearCollect(
    GroupedCollection,
    GroupBy(MyCollection, "LastName", "GroupedData")
)

This will create a new collection called GroupedCollection that contains the grouped data, with each group represented by a separate record. The second parameter of the GroupBy function specifies the name of the field to group by LastName, and the third parameter specifies the name of the field that will contain the grouped data GroupedData.

The resulting GroupedCollection collection will look like this:

GroupedDataLastName
Table({ First Name: “John”, LastName: “Smith”, Age: 25 },{ FirstName: “Bob”, LastName: “Smith”, Age: 35 })Smith
Table({ First Name: “Jane”, LastName: “Doe”, Age: 30 },{ FirstName: “John”, LastName: “Doe”, Age: 40 })Doe

Note that the GroupedData field contains a table of records that belong to each group.

To ungroup the data in GroupedCollection, we can use the Ungroup function:

ClearCollect(
    UngroupedCollection,
    Ungroup(GroupedCollection, "GroupedData")
)

This will create a new collection called UngroupedCollection that contains the ungrouped data. The second parameter of the Ungroup function specifies the name of the field that contains the grouped data GroupedData.

The resulting UngroupedCollection collection will look like this:

FirstNameLastNameAge
JohnSmith25
BobSmith35
JaneDoe30
JohnDoe40

Note that the data is no longer grouped by the LastName column.

I hope this example helps you understand how to use the GroupBy and Ungroup functions in Power Apps collections.

Leave a Comment