Getting a random value from a JavaScript array
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);
It's 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]);
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
I'm releasing these code snippets into the public domain, under the terms of the CC0 1.0 license.