Skip to content

Instantly share code, notes, and snippets.

@jzntam
Created April 6, 2016 18:13
Show Gist options
  • Save jzntam/2448238a3d263b3371f2d0b7196c9304 to your computer and use it in GitHub Desktop.
Save jzntam/2448238a3d263b3371f2d0b7196c9304 to your computer and use it in GitHub Desktop.

Fisher-Yates Knuth Method

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While elements are avaiable to shuffle
  while (0 !== currentIndex) {

    // Pick an element
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment