How to get a random element from an array

JavaScript polyfill, by , Tuesday, April 8th, 2014

Fetching a random element from an array is pretty straight forward in JavaScript, if you are aware of how to use the build in Math.random() method. What this method does, is simply return a random number from and including 0 to but excluding 1, or in more formal terms [0-1[. From this it should be obvious, that if we take this random number and multiply it with the length of the given array, and then floor it, we should get a random index number, so lets try that out;

  1. var goodTeas = ['Thai tea', 'Indian Chai', 'Hong Kong Milk Tea'],
  2. randomTea = goodTeas[(function () {
  3. return Math.floor(Math.random() * goodTeas.length);
  4. }())];

The randomTea variable now contains one of the three teas mentioned in the goodTeas array. Of course you can also write a function that gives you a random index number, or extend the Array.prototype to have such a method. Extending the prototype of a build in object is not recommended to do, as you could risk conflicting with future native implemented features, but since this is just to make a point, lets look at how to do that anyway;

  1. Array.prototype.getRandomElement = function() {
  2. "use strict";
  3. return this[Math.floor(Math.random() * this.length)];
  4. };

This would make it very convenient to get a random element from an array, as you can call it directly on any array, just like any other build in Array methods.