Tech Tip: How to shuffle items in a collection

PRODUCT: 4D | VERSION: 19 R | PLATFORM: Mac & Win

Published On: March 13, 2023

In certain scenarios, randomizing the order of items in a collection may be desired. One way to do this is to use the .sort( ) function along with the Random command.

For example, say there is a sorted collection of numbers 1 to 10:

$nums:=New collection(1; 2; 3; 4; 5; 6; 7; 8; 9; 10) // [1,2,3,4,5,6,7,8,9,10] |

To shuffle those numbers, sort the collection with a formula that compares a random integer with another integer:

$nums.sort(Formula(((Random%2)+1)>1)) // [3,6,1,2,7,4,8,5,10,9] |

In the formula, (Random%2)+1 returns either 1 or 2 with equal probability. Thus, the comparison formula will return True or False with random chance, and .sort( ) will order the items randomly.

NOTE: Formula object is only supported as a parameter in .sort( ) starting in v19 R7. If v19 LTS is being used, another project method that performs the comparison must be created, and the method name must passed as a parameter in .sort( ).