What is Fisher–Yates shuffle in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Fisher-Yates shuffle algorithm

This algorithm is to shuffle the elements in an array. To shuffle the elements in an array we can write our own logic, but many developers think that Fisher-Yates modern shuffle algorithm is the best way to shuffle the elements in an array. This algorithm has the following steps.

Steps to follow

  • According to this algorithm we should loop the array from back to front. For instance, in the following example, we have an array consisting of 8 elements(A,B,C,D,E,F,G,H) from index 0 to index 7. So the first loop pass will affect the element at the last index 7 that is H.
  • Next step is to generate a random number (random index) between the selected index 7 and index 0. For suppose let the random index be 3.
  • After getting the random index swap the elements that are in the selected index and at random index.The element at the random index in the provided array is D. So after swapping, the array will be changed to A,B,C,H,E,G,F,D. 
  • In the second loop pass just ignore the last index (since it is already looped) and try to find the random index between index 0 and index 6 that is between the elements A and F. Let the generated random index be 2.
  • After getting the random index let's swap the elements at indexes at 6 and 2. Now the array will look as A,B,F,H,E,G,C,D.
  • This algorithm follows the same pattern that is it ignores index 6 and starts finding random index between index 5 and index 0 and so on until it reached the index 1. It can't take index 0 to loop because there are no indexes less than 0 for swapping purpose.
  • Note that there is a possibility that generated random index be selected loop index. For instance, let the loop is running between selected index 4 and index 0. let the random index generated be 4. Then the value at the index 4 will remain at the same position.

The following example illustrates Fisher-Yates modern shuffle algorithm


Live Demo

   var arr = ['A','B','C','D','E','F','G','H']
   var i = arr.length, k , temp;      // k is to generate random index and temp is to swap the values
   while(--i > 0){
      k = Math.floor(Math.random() * (i+1));
      temp = arr[k];
      arr[k] = arr[i];
      arr[i] = temp;


C,F,H,D,A,G,E,B  // note that output will change for every iteration.
Updated on 30-Jul-2019 22:30:26