views:

104

answers:

2

I have one array like this:

var arr 1 = ["a", "b", "c", "d"];

How can I randomize / shuffle it?

+7  A: 

Credit goes here.

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;
   }
}

Some more info about the algorithm used.

ChristopheD
... except that Math.random() is not random at all, and therefore the Fisher-Yates Shuffle will not randomly shuffle for sufficiently large sets. Just pointing this out in case someone attempts to the latter.
prometheus
@prometheus , what do you mean math.random is not random? why is it called math.random if it isnt?
Click Upvote
Because when the ECMAScript standard was conceived, "web programmers" barely used Javascript for anything other than web page gimmicks, and as such naming it random() was appropriate. For what it's worth, the Mozilla documentation clearly states that random() is pseudo-random: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Math/Random
prometheus
A: 

One implementation:

["a", "b", "c", "d"].sort(function() { return Math.floor(Math.random()*3 -1)});

[Edit] Much simpler implementation from here.

["a", "b", "c", "d"].sort(function() { return 0.5 - Math.random();});
Chetan Sastry
For anyone thinking of actually using this, I encourage you to read this first: http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
Shog9