How to pick a random array member? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to pick a random array member?

I'm trying to make a simple code that picks something random from the array and alerts it to the user.

2nd Dec 2017, 3:27 AM
Needforrun
Needforrun - avatar
2 Answers
+ 4
You need to generate a random number from 0 to array.length and use that as an index. Math.random() will return a number between 0 and 1, so all you need to do is multiply and round down to a whole number. let random_index = Math.floor(Math.random() * my_array.length); let my_random_element = my_array[random_index];
2nd Dec 2017, 3:35 AM
Schindlabua
Schindlabua - avatar
+ 13
Here's how to use JavaScript's random() function: Math.floor((Math.random() * maxValue) + minNumber); For example, for an array with 100 items: Math.floor((Math.random() * 100); //Gives 0 - 99
2nd Dec 2017, 3:34 AM
Tamra
Tamra - avatar