Randomizing elements in an array?

I wrote this a while ago and it so happens to fit what you’re looking for. I believe it’s the Fisher-Yates shuffle that ojblass refers to:

Array.prototype.shuffle = function() {
   var i = this.length;
   while (--i) {
      var j = Math.floor(Math.random() * (i + 1))
      var temp = this[i];
      this[i] = this[j];
      this[j] = temp;
   }

   return this; // for convenience, in case we want a reference to the array
};

Note that modifying Array.prototype may be considered bad form. You might want to implement this as a standalone method that takes the array as an argument. Anyway, to finish it off:

var randomSubset = originalArray.shuffle().slice(0,13);

Or, if you don’t want to actually modify the original:

var randomSubset = originalArray.slice(0).shuffle().slice(0,13);

Leave a Comment