Getting a random value from a JavaScript array

Getting a random value from a JavaScript array

Consider:
var myArray = [‘January’, ‘February’, ‘March’];

How can I select a random value from this array using JavaScript?

Solutions/Answers:

Solution 1:

var rand = myArray[Math.floor(Math.random() * myArray.length)];

Solution 2:

I’ve found it even simpler to add a prototype function to the Array class:

Array.prototype.randomElement = function () {
    return this[Math.floor(Math.random() * this.length)]
}

Now I can get a random array element by just typing:

var myRandomElement = myArray.randomElement()

Note that this will add a property to all arrays, so if you’re looping over one using for..in you should use .hasOwnProperty():

for (var prop in myArray) {
    if (myArray.hasOwnProperty(prop)) {
        ...
    }
}

(That may or may not be a hassle for you.)

Solution 3:

If you’ve already got underscore or lodash included in your project you can use _.sample.

// will return one item randomly from the array
_.sample(['January', 'February', 'March']);

If you need to get more than one item randomly, you can pass that as a second argument in underscore:

// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);

or use the _.sampleSize method in lodash:

// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);

Solution 4:

Say you want to choose a random item that is different from the last time (not really random, but still a common requirement)…

Building upon the answer by @Markus, we can add another prototype function:

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];
   }
}

And implement like so:

var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)

Solution 5:

Prototype Method

If you plan on getting a random value a lot, you might want to define a function for it.

First, put this in your code somewhere:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

Now:

[1,2,3,4].sample() //=> a random element

Code released into the public domain under the terms of the CC0 1.0 license.

Solution 6:

The shortest version:

var myArray = ['January', 'February', 'March']; 
var rand = myArray[(Math.random() * myArray.length) | 0]