shuffle an array in javascript

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.tsx
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
200 chars
8 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.tsx
const myArray = [1, 2, 3, 4, 5];
shuffleArray(myArray);
console.log(myArray);
// output: [5, 2, 4, 1, 3] (randomly shuffled)
125 chars
5 lines

gistlibby LogSnag