Randomly Shuffle a JavaScript Array

by Rick 19. August 2011 14:05

For one reason or another, I needed to randomly shuffle an array in JavaScript.  Using the prototype object, one is able to add custom properties and methods to all instances of native, and custom, objects.  The code below extends the Array object to include a shuffle function and demonstrates its usage.

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

var array1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var array2 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19];

array1.shuffle();
array2.shuffle();

I've encountered at least one knee jerk reaction that suggests... "DON'T MODIFY OBJECTS YOU DON'T OWN!?!"  I tend to take advice like that with a grain of salt.

Tags: , , , , , ,

JavaScript