I am a late comer to this question. If you don't mind adding a method to Array, you can:
Array.prototype.pickARandomElement = function() {
return this[Math.floor(Math.random() * this.length)];
}
test run:
> [10, 123, 777].pickARandomElement()
10
> [10, 123, 777].pickARandomElement()
777
> [10, 123, 777].pickARandomElement()
777
> [10, 123, 777].pickARandomElement()
123
The following is just for fun:
Array.prototype.pickARandomElement = function() {
return this.sort(function() { return Math.random() - 0.5; })[0];
}
it is like shuffling a deck of cards and returning the top card. But its time complexity is O(n log n) so I wouldn't really use it, and it is just for fun. The first solution here is a solution with O(1).