Mathematically Elegant way to Flatten an Array of Arrays in Power Automate
/When working with data in Power Automate, you may encounter nested arrays (arrays within arrays)—especially when dealing with JSON responses, SharePoint lists, or API results. However, many Power Automate actions require a flat array to work properly.
In this post, I'll show you a mathematically elegant way to flatten an array of arrays into a single-level array using Power Automate expressions.
Understanding the Problem
Let's say you have the following array:
[ ["Ford", "Toyota"], ["BMW", "Audi"], ["Honda", "Nissan"] ]
Instead of dealing with nested arrays, you want to flatten it into a single array:
["Ford", "Toyota", "BMW", "Audi", "Honda", "Nissan"]
The slow way - Array variable
The slow way is to use an array variable, then while looping through the top level array, append or union the results into the array variable.
Variables are so slow I don’t even want to make them and add a picture.
The faster way - String manipulation
Convert the array into JSON string, remove the extra array [ and ] characters, re-construct the array in string, and convert back to JSON.
This is a method I was using, it’s much quicker, but has a risk of needing to be careful when removing bracket characters. If you have nested JSON objects this needs more care.
The new fastest way - div and mod flattening
To understand this - you need two numbers: m and n
m = number of elements in the top array
n = number of elements in the child array
Create a range of the total result size of the array (m) * (n)
Use select - loop through this range of numbers, then for each, select the nested result using:
outputs(‘nested-items’)?[ div( item(), outputs(‘n’)) ]?[mod( item(), outputs(‘n’)) ]
do you see how elegant this is 🤔
what’s going on here?
let’s picture for each of the 6 elements above.
0 = array[0][0] div(0, 2) = 0, mod(0,2) = 0
1 = array[0][1] div(1, 2) = 0, mod(1,2) = 1
2 = array[1][0]
3 = array[1][1]
4 = array[2][0] div(4, 2) = 2, mod(4,2) = 0
5 = array[2][1]
so in one select, we can flatten an (m * n) -sized array.
What if my child array is irregularly sized?
That’s OK. By using ?[n] Select will return null for that element, so we can follow the select with a filter-array to remove the nulls.
Bonus
This works wonderfully with Pieter’s Method, which returns array of Body jsons.
Bonus
This works well for cross-join of two arrays, and then flattening them into one.
(These bonus ideas are massive additional blog posts let me know if want to read them…)