Solution 1: Fisher-Yates Array Shuffle
- Start at the end of your array.
- Choose a random index within your array
- Swap the two values
- Repeat down your array until all indexes are swapped.
This approach will give you a lot of unpredictability, and although it’s quite efficient, the size of the array will affect its speed. Because we’ll need to create some code to do the shuffle, it’s ideal to place the algorithm in a reusable function, preferably in a utility file that you can use throughout your project.
The Fisher-Yates shuffle, named after its authors Ronald Fisher and Frank Yates, was originally described in 1938. The Knuth shuffle is another name for this technique.
Solution 2: Sort One Liner
This approach is popular because of its clarity and simplicity. It does, however, have several severe flaws. For big arrays, it is inefficient, and many items might be left unshuffled, resulting in poor overall randomization.
This technique should only be used on tiny arrays when a large proportion of randomization isn’t required.
Even though it has a larger syntactic payload, the first Fisher-Yates approach from these two possibilities is strongly recommended.