Recently, I had to flatten a 2D array into a distinct array in Power Automate. I found doing a nested loop slow and costly because of the extra actions. Below is the most efficient solution I have found. This solution will take an array of contacts with a nested array of phone numbers and produce a distinct list of phone numbers. TLDR, the union function, can merge two arrays in a compose expression. This can be used to merge a 2D array through a loop. The union function will also distinct the merged lists.
uses a union expression to merge the phone numbers in the array variable with the phone numbers of the contact being processed in the loop. The union function also distinct the phone numbers. Notice how final output lists phone number 9999-999-999 once but Batman and Cat Woman both share the phone number 9999-999-999.
JSON Array of Contacts
Final Output of Phone Numbers
The Power Automate Solution
Trigger—This is a scheduled trigger for ease of development and testing. The configuration is nothing special. It is set to run every 9 months to ensure it doesn't run too often.
Compose - Contacts and Phone Numbers - contains the JSON array of contacts each with multiple phone numbers that will be processed into a single array of distinct phone numbers.
Initialize variable - Distinct Phone Numbers - initializes an empty array that will be used to store the distinct phone numbers.
Apply to each - Contact - Loop through each contact in the JSON set on "Compose - Contacts and Phone Numbers" action.
Expression: @{outputs('Compose_-_Contacts_and_Phone_Numbers')}
Settings: Concurrency set to 1. It is important to set concurrency 1, otherwise the Phone Number array variable will not have all phone numbers set.
Compose - Merged Phone Numbers - uses a union expression to merge the phone numbers in the array variable with the phone numbers of the contact being processed in the loop. The union function also distinct the phone numbers. Notice how final output lists phone number 9999-999-999 once but Batman and Cat Woman both share the phone number 9999-999-999.
Expression: @{union(variables('Phone Numbers'), item()?['phoneNumbers'])}
Set variable - Merged Phone Numbers - sets the Phone Numbers array to the new list of merged phone numbers from the above action "Compose - Merged Phone Numbers".
Expression: @{outputs('Compose_-_Merged_Phone_Numbers')}
Compose - Distinct Phone Numbers - displays the final distinct list of phone numbers.
Comments