Return to Snippet

Revision: 55738
at February 20, 2012 19:54 by devnull69


Initial Code
// (C) Stephen "felgall" http://www.codingforums.com/showthread.php?t=252059

Array.prototype.shuffle = function() {
   var s = [];
   while (this.length) s.push(this.splice(Math.random() * this.length, 1));
   while (s.length) this.push(s.pop());
   return this;
}

Initial URL

                                

Initial Description
The usual way to shuffle an array uses the .sort() method with Math.round(Math.random())-0.5
This solution is highly biased based on the sort algorithm used by the browsers. A sort comparison operation has to fulfill the condition "if a>b then b<a" for two consecutive calculations which won't work with this. So here is a possible unbiased solution for a .shuffle() method

Initial Title
Array shuffle without bias

Initial Tags
javascript, array

Initial Language
JavaScript