Last active
August 29, 2015 14:03
-
-
Save jawinn/9e9e81df8d54b1291c2d to your computer and use it in GitHub Desktop.
Random JS Array Element, Different than the Last One
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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