Tag Archives: Frank Yates

Javascript – How to Shuffle an array

You can use the following function to shuffle a Javascript array. Kudos to Ashley Pond V. The author applies the Fisher-Yates shuffle algorithm which is also known as the Knuth shuffle in Javascript.

function fisherYates(myArray) {
  var i = myArray.length;
  if (i == 0) return false;
  while(--i) {
    var j = Math.floor(Math.random()*(i+1));
    var tempi = myArray[i];
    var tempj = myArray[j];
    myArray[i] = tempj;
    myArray[j] = tempi;
  }
}

Done =)

Reference: Randomize arrays in JavaScript with the Fisher-Yates shuffle algorithm