Getting a random value from a JavaScript array

Getting a random value from a JavaScript array

Its a simple one-liner:

const randomElement = array[Math.floor(Math.random() * array.length)];

For example:

const months = [January, February, March, April, May, June, July];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);

If youve 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);

Getting a random value from a JavaScript array

You may consider defining a function on the Array prototype, in order to create a method [].sample() which returns a random element.

First, to define the prototype function, place this snippet in your code:

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

Later, to sample a random element from the array, just call .sample():

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

Im releasing these code snippets into the public domain, under the terms of the CC0 1.0 license.

Leave a Reply

Your email address will not be published.