How to shuffle elements in the DataWeave array?

In this short article, I show you how to shuffle your array. In other words, we will randomly reorder the elements in the array. So let’s get started.

Sample case

I have an array of numbers like

[ 1, 2, 3, 4, 5, 6, 7, 8 ]

Anytime I run the operation I would like to receive different order of elements in the array. Here are a couple of examples

[ 1, 3, 2, 5, 4, 6, 8, 7 ]
[ 5, 1, 3, 6, 2, 4, 8, 7 ]
[ 7, 1, 3, 2, 8, 6, 4, 5 ]

Real life scenario

I built it recently to randomly order the checked-in attendees on Warsaw MuleSoft Meetup. After reordering, I can select lottery winners starting from the top of the array. Here is a sample result of the shuffled array of attendees

Attendees ordered randomly
Attendees ordered randomly

I can pick the first three, so Adam, Janet, and John. If however, one of them is not currently present at the Meetup I can select the next person in the array. For example, Janet did not respond, so I pick Mark W, etc. Now I have my Lottery winners:

Selected winners of the lottery
Selected winners of the lottery

Shuffle function

DataWeave does not have a shuffle function however you can use orderBy to implement that behavior. Below you can see my shuffle function. The orderBy function takes as a parameters criteria, that is used to reorder the elements in the array. In our case, the reorder should happen randomly. That is why I used the random function as a criterium. The random function returns a random decimal number between 0.0 and 1.0. As a result, we have a randomly sorted array

fun shuffle(arr: Array) =
    arr orderBy random()
Testing shuffle function using DataWeave playground
Testing shuffle function using DataWeave playground

You can find a module with a shuffle function on my GitHub repository here. In my previous article I explained how to create your DataWeave module and using it.

Summary

The shuffle function is plain and simple. We have just used two already available functions. MuleSoft team is constantly developing and improving DataWeave modules, so it may be just a matter of time when such function will be introduced. Once it happens I will let you know.

Cheers

How to shuffle elements in the DataWeave array?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top