Last Updated on 30/05/2021 by Patryk Bandurski
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.
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
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:
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()
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.