Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 494
Sarah Avatar asked Dec 29 '10 00:12

Sarah


People also ask

How do I get random in 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.

Can you use math random on array?

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.

How do you randomly select an item from an array in Java?

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.


2 Answers

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]);
like image 181
Jacob Relkin Avatar answered Sep 21 '22 13:09

Jacob Relkin


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); 
like image 45
Brendan Nee Avatar answered Sep 18 '22 13:09

Brendan Nee