Consider:
var myArray = ['January', 'February', 'March'];
How can I select a random value from this array using JavaScript?
Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.
random() Let's write a function to return a random element from an array. We can use Math. random() to generate a number between 0–1 (inclusive of 0, but not 1) randomly.
Java has a Random class in the java. util package. Using it you can do the following: Random rnd = new Random(); int randomNumberFromArray = array[rnd.
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]);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With