Yesterday I was asked about how to avoid variables when you want an index number of the item processed by an apply to each step.
Variables or Compose?
The variables or compose question is quite an old question in the Power Automate world. The main issue with variables is that inside an apply to each variables lock the processing of items by the Apply to each. This disables the possibility to run the processing in parallel using the Concurrency settings on an apply to each.
And when when I looked at some forum posts the only solution given was to use variables.
As also mentioned in the above community forum post using variables is the only known option. (up to now! Just keep reading). But we want to avoid variable when performance is important and we have a lot of items to process. Make that flow that runs for hours run within seconds!
A couple of approaches that you could consider:
- The function iterationIndex does exist but that only works on Do until loops and not on apply to each loops.
- Adding a column to each item you can’t do as there is no other way of counting the items while processing the items
Making it all work!
I’m going to start with a simple flow. In my case I use a Compose action to build an array.
And as I run the flow, I can see the objects in my array:
If I process this array in an apply to each, I will have the starting point of my problem. I will not be able to get to the 1 – 4 number as displayed in the apply to each step:
But how about if I processed the IDs? So I would create an array that just contains the IDs using the range function.
When I run the above flow I will find a list of numbers. In my case I generated the numbers 0-3. The ID that I want is 1-4. But you will find out shortly why I’m doing this.
In my apply to each I will now take the array of IDs rather than the items that I want to add the ID to.
Notice that the ID is created using the following expression:
And the item is selected form my array of items with the following line:
The arrays start with item 0 hence the list of IDs starting with 0 as well.
And now finally, I could take the list of items using Pieter’s method so that I get a single array with IDs: