The Power Automate Sort function enables the ordering of items in a collection. The objects in the collection can be sorted using a key with a basic data type.
In this article, I’ll introduce you to the sort function and will provide a step-by-step guide on how to use the function in a Microsoft flow.
Power Automate Sort Function
Order elements within a collection. The objects within the collection can be sorted based on any key with a simple data type.
Syntax
sort([<collection>], <sortBy>?)
Input parameters
- collection (mandatory): The collection to be sorted.
- sortBy (optional): The key of the property that should be used for sorting the collection.
Return value
- Returns the sorted collection.
Power Automate Sort Expression Examples
The most simple examples of a sort expression for sorting an array of numbers:
sort(createArray(3,1,2))
=> [1,2,3]
Power Automate sort reverse order (descending order)
To sort an array in reverse order, you need to sort first in ascending order and then reverse the order with the Power Automate reverse function.
reverse(sort(createArray(3,1,2)))
=> [3,2,1]
Using reverse alone is not enough, because the reverse function simply reverses the order without sorting.
Power Automate Sort Object by column
We have this object as input and want to sort it by last name:
{
"persons": [
{
"firstname": "Sally",
"lastname": "Smith"
},
{
"firstname": "John",
"lastname": "Doe"
}
]
}
You can use the following sort expression for this:
sort(variables('persons')?['persons'],'lastname')=> [3,2,1]
You will get a sorted object:
[
{
"firstname": "John",
"lastname": "Doe"
},
{
"firstname": "Sally",
"lastname": "Smith"
}
]
How To Use The Power Automate Sort Function
Follow the steps to use the Power Automate Sort function in a flow.
-
Create a new flow with trigger ‘Manually trigger a flow’
New flow
-
Add a new step by clicking on ‘+ New step’
Add a new step
-
Search for ‘initialize’ and click on ‘Initialize variable’
Add Initialize variable action
-
Setup Initialize variable: 1) Provide a name, 2) select type Array, 3) Set value to ‘[“orange”,”apple”,”melon”]’
Setup variable
-
Add a compose step by searching for ‘compose’ and clicking on ‘Compose’
Add Compose action
-
Setup compose action: 1) click into Inputs (popup appears), 2) click on ‘Expression’, 3) set expression to ‘sort(variables(‘fruits’), 3)’ 4) click on ‘OK’
Setup sort expression in Power Automate
-
Save and do a test run
Result test run – Power Automate sort function example