Skip to content

Instantly share code, notes, and snippets.

@jawinn
Last active August 29, 2015 14:03
Show Gist options
  • Save jawinn/9e9e81df8d54b1291c2d to your computer and use it in GitHub Desktop.
Save jawinn/9e9e81df8d54b1291c2d to your computer and use it in GitHub Desktop.
Random JS Array Element, Different than the Last One
// via http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array
// usage: var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement);
Array.prototype.randomDiffElement = function(last) {
if (this.length == 0) {
return;
} else if (this.length == 1) {
return this[0];
} else {
var num = 0;
do {
num = Math.floor(Math.random() * this.length);
} while (this[num] == last);
return this[num];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment