Here is a little snippet that you may find useful if you ever have to randomize the contents of an array:

``````
Array.prototype.randomize = function() {
var t, j, ret = this.slice(0), i = ret.length;
while(--i > 0) {
t = ret[j = Math.round(Math.random() * i)];
ret[j] = ret[i];
ret[i] = t;
}
return ret;
};
``````

Here is an example of how to use it with an array:

``````
// The array of random names.
var names = [
"Amy",
"Greg",
"Jen",
"Matthew",
"Owen",
"Richard",
"Stacy",
"Tiffany",
"Victoria",
"Wanda"
];
// Randomize the array of names.
var randomOrder = names.randomize();
// Display the names.
alert("This will be the order:\n- " + randomOrder.join("\n- "));
``````

The above example will show the names that are in the `names` array in random order. If we are using a JavaScript library that defines `Array.prototype.map()`) (such as jPaq) or we know that the page will be viewed on newer browsers (such as Firefox 3.5+ or Google Chrome), we could take the following approach to actually display the number order next to each name:

``````
// The array of random names.
var names = [
"Amy",
"Greg",
"Jen",
"Matthew",
"Owen",
"Richard",
"Stacy",
"Tiffany",
"Victoria",
"Wanda"
];
// Randomize the array and display the number of each name to the left of the
// name.
var randomOrder = names.randomize().map(function(name, i) {
return ++i + ". " + name;
});
// Display the names in random order.
alert("This will be the order:\n" + randomOrder.join("\n"));
``````
Categories: BlogJavaScriptJScript

### 1 Comment

#### Chris West's Blog » JavaScript – Array.prototype.randomize() · July 7, 2011 at 7:06 PM

[…] Continued here: Chris West's Blog » JavaScript – Array.prototype.randomize() […]