How to reverse an Array/ collection in Power Apps Canvas apps

Hello everyone and welcome to my blog. In today’s blog I will show you on how to reverse an array/ collection in canvas apps.

Let’s get started. I have collection of fruits which I will reverse

ClearCollect(fruits,"apple", "banana", "watermelon", "orange")

Most of the programming languages have in-built function to reverse an array. Unfortunately, Power Apps does not have an inbuilt function to accomplish the same. We need to use few functions to achieve this functionality.

Below is the code to reverse the array.

ClearCollect(
    itemIndexes,
    CountRows(fruits)
);
ForAll(
    fruits,
    Collect(
        reversedFruits,
        Index(
            fruits,
            Last(itemIndexes).Value
        )
    );
    Collect(
        itemIndexes,
        Last(itemIndexes).Value - 1
    )
)

Let’s dissect the formula. Below is the first part of the formula.

To reverse an array the first and most obvious thing is to iterate through the array in reverse order. So we need to start iteration from the end of the Array. Below is the formula for the same.

ClearCollect(
    itemIndexes,
    CountRows(fruits)
);

I used collection because in Power Apps ForAll constuct we cannot use Set or UpdateContext function to set a variable value. And since we are going to start from the end, the first item in the collection is the length of the fruits collection.

The next is the ForAll statement. Let’s concentrate on the first action inside ForAll statement

Collect(
        reversedFruits,
        Index(
            fruits,
            Last(itemIndexes).Value
        )
    );

I am using the Index function to extract the element at specified position in the collection. I get the iteration index from the itemIndexes collection declared in earlier step.

Now the final part is to decrease the iteration index before the next iteration which is achieved using the below formula.

Collect(
        itemIndexes,
        Last(itemIndex).Value - 1
    )

After every iteration, I store the previous index in the collection. So the next index to work on is always the last item of the collection.

Well that’s it. I have the collection reversedFruits having the items of fruits collection in reverse.

If you are wondering if this shall work with tables too, yes it will. The same formula will continue to work.. Below is the fruits table.

After I execute the same formula, below is the reverseFruits table

Hope you liked this post. If this post has helped you, you can buy me a coffee.

To learn more interesting stuffs of Microsoft.NET and Power Platform, you can subscribe to my blog. Link on right hand pane.

You can also check out the below posts.

Debajit Dutta
Business Solutions MVP