How to use Fisher-Yates (Knuth) shuffle In Javascript

This algorithm, also known as the Knuth Shuffle, involves iterating through the array in reverse order and swapping each element with a randomly selected element that comes before it.

Example: The provided code uses the Fisher-Yates (Knuth) shuffle method to shuffle elements in a JavaScript array.

Javascript




function fisherYatesShuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}
 
const arr1 = [1, 2, 3, 4, 5];
const shuffledArr1 = fisherYatesShuffle([...arr1]);
console.log(shuffledArr1);


Output

[ 2, 4, 5, 1, 3 ]

How to Shuffle the Elements of an Array in JavaScript ?

Shuffling arrays is an elementary operation in programming that helps to introduce change into data sets. There are several approaches in JavaScript using which one can shuffle the elements of the array which are as follows:

Table of Content

  • Using Fisher-Yates (Knuth) shuffle
  • Using sort with Math.random
  • Using array.map with Math.random
  • Using array.reduce with Math.random
  • Using generator functions

Similar Reads

Using Fisher-Yates (Knuth) shuffle

This algorithm, also known as the Knuth Shuffle, involves iterating through the array in reverse order and swapping each element with a randomly selected element that comes before it....

Using sort with Math.random

...

Using array.map with Math.random

The approach uses the `sort` function in combination with a custom comparison function which makes use of `Math.random()` for introducing randomness. When the array is effectively shuffled by subtracting random values, it is a result of the stability of the sorting algorithm....

Using array.reduce with Math.random

...

Using generator functions

This method shuffles an array effectively using Math.random(). The original value plus a randomly assigned number will be assigned as an element into an object in the `randomSort(array)` function. Sorting takes place depending on how much these numbers are randomly generated thereby leading to an array that is randomly sorted....

Contact Us