1. Computing & Technology

Shuffle

If you are used to programming your server side code using PHP then you have probably used the shuffle() option to "sort" an array into random order. Javascript doesn't come with an equivalent function but you can easily add a shuffle method to all of our arrays to make it really easy to randomise their content using the following short piece of code:

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

With that code in place we can shuffle the content of our array as easily as we can sort it. Here's an example:

var myary = [0,1,2,3,4,5,6,7,8,9];
myary.shuffle();

After running those two lines we now have an array of numbers from 0 through 9 in a random order.

Note that this has only shuffled the content of the array, you will still need to add whatever code you need to actually use the content of your shuffled array. (When I was testing the code I took the easy way out and just set up a loop to output the entries using document.write).

Of course this is still a bit different from the way shuffle works in PHP but I think myary.shuffle() is a better way to call it than shuffle(myary) anyway. If you really insist on its working the same way as in PHP then you'd define the shuffle function like this instead:

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

©2012 About.com. All rights reserved.

A part of The New York Times Company.