Sort a collection or array of objects in Power Automate with sort order.

Hello everyone and welcome to my blog. In today’s blog I will discuss the following requirements

  • How to sort an simple array
  • How to sort an array or collection of by object property
  • How to specify ASCENDING or DESCENDING sort order for collections in Power Automate

Let’s get started. We will start with simple example and then move to more complex scenarios here. We shall use the Power automate sort function for all purposes.

The final example in the blog show how to specify a sort order or order by clause when using sort function in Power Automate. If that is your requirement, you can skip to the last section of the blog for the same.

Sort a collection or array of string values

I have a simple array of string values.

Below is the expression to sort the array.

Well that was easy. You can similarly sort an array of string or integers or other data types. But how about sorting of objects.

Sort a collection or objects by an object property

Below is an array of object I want to sort based on “name” property.

[
   {
      "name": "Debajit",
      "type": "employee",
      "id": 1
   },
   {
      "name": "Chandana",
      "type": "employee",
      "id": 2
   },
   {
      "name": "Andrew",
      "type": "consultant",
      "id": 3
   }
]

For this we will use the sort function again but this time with the second parameter of sort key. Below is the expression to do the same.

sort(variables('arrSample'), 'name')

As of the time of writing this blog, there is no way to sort an object collection by multiple object properties.

Now the big question. How about the Sort order or the ubiquitous order by clause.

Unfortunately there is no sort order parameter. However don’t be disappointed.

By default, the sort function sorts in ascending order. There is another function reverse which reverses the items of an array or collection.

Let’s take the same collection we used earlier. And this time our requirement is to sort the collection by descending order of name property.

[
   {
      "name": "Debajit",
      "type": "employee",
      "id": 1
   },
   {
      "name": "Chandana",
      "type": "employee",
      "id": 2
   },
   {
      "name": "Andrew",
      "type": "consultant",
      "id": 3
   }
]

Using the expression sort(variables(‘arrSample’), ‘name’), below is the output.

Remember, the default sorting when you use the sort function is always ascending order. Now to sort the array in descending order of name property, we just need to use the reverse expression on the output of the sort function.

Below is the output of the reverse function.

Screenshot below of the power automate flow with expressions.

Hope this helped. To stay updated with similar interesting topics, please subscribe to my blog.

Debajit Dutta
Business Solutions MVP