To shuffle an array in JavaScript, we can use the Fisher-Yates (also known as Knuth) Shuffle algorithm. This algorithm randomly shuffles the elements of an array in-place.
Here's how to implement the Fisher-Yates Shuffle algorithm:
index.tsx200 chars8 lines
The array
parameter is the array that we want to shuffle.
The for
loop starts from the last element of the array and iterates backwards to the first element. In each iteration, a random index j
is generated between 0 and i
using the Math.random
function. The current element at index i
is then swapped with the element at index j
.
Finally, the shuffled array is returned.
Here's an example usage of the shuffleArray
function:
index.tsx125 chars5 lines
gistlibby LogSnag