DEV Community

Barret Blake
Barret Blake

Posted on • Originally published at barretblake.dev on

Function Friday – Chunk, Sort & Reverse

Power Automate has added a number of new expression functions and features recently. This time around I’ll take a look at three of those new functions: chunk, sort and reverse.

Chunk

The chunk function lets you break up strings or arrays into blocks of equal length. The format is as follows:

chunk(<string>, <length>)
chunk(<array>, <length>)
Enter fullscreen mode Exit fullscreen mode

The first parameter is the string or array you want to break apart. The second parameter is the length you want for each chunk. The result that is returned is an array of chunks. If the array or string doesn’t break apart evenly based on the requested length, the remainder will be in the last array element.

Examples:

chunk([0,1,2,3,4,5,6,7,8,9], 3) // returns [[0,1,2],[3,4,5],[6,7,8],[9]]
chunk('Hello there my friend', 5) // returns ['Hello',' ther','e my ','frien','d']
Enter fullscreen mode Exit fullscreen mode

Sort

This one is a long overdue function. It does exactly as promised. It takes an array of objects and sorts them. The pattern is as follows:

sort(<array>, <sortBy>)
Enter fullscreen mode Exit fullscreen mode

The first parameter is the collection of objects you want to sort. The second parameter is optional and defines the key you want to use for sorting the objects. This parameter is only needed when the collection is an array of JSON objects. For arrays of numbers or strings, the sorting is done as you would expect, by numerical order or by alphabetical order.

Examples:

sort([1,5,3,2,0]) // returns [0,1,2,3,5]
sort(['Frank','Garth','Albert','Amanda','Emily']) // returns ['Albert','Amanda','Emily','Frank','Garth']

sort(createArray(json('{ "first": "Amanda", "last": "Blake" }'), json('{ "first": "Caleb", "last": "Anders" }'), "last")  
   // returns [{ "first": "Caleb", "last": "Anders" }, {"first": "Amanda", "last": "Blake" }')]
Enter fullscreen mode Exit fullscreen mode

Reverse

Another long overdue function, reverse takes a collection and returns it in reverse order. The pattern:

reverse(<array>)
Enter fullscreen mode Exit fullscreen mode

Example:

reverse([0,1,2,3,4]) // returns [4,3,2,1,0]
Enter fullscreen mode Exit fullscreen mode

It doesn’t matter what the array data type is. This function just reverses the order of the elements in that array.

Conclusion

So there we have 3 of the new functions for Power Automate. While the usefulness of chunk is somewhat limited, sort and reverse have been wanted for quite a long time and they will come in quite handy for many use cases. I’m glad to see them finally arrive.

The post Function Friday – Chunk, Sort & Reverse first appeared on Barret Codes.

Top comments (0)