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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.