Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have an array that has sequential array keys and I need to randomly select one of the keys... what's the best way to do that?

share|improve this question

3 Answers 3

up vote 10 down vote accepted

Math.random() will generate a number between 0 and 1.

var key = Math.floor(Math.random() * arr.length);
share|improve this answer
    
Only using the array length will result in never actually selecting the last item in the array, except in the extremely rare situation when the random number selected is 1.0000. See stackoverflow.com/a/16111426/303694 –  Denis Gorbachev Sep 16 '13 at 14:15
6  
@DenisGorbachev's statement is incorrect. Math.random() returns 0 inclusive to 1 exclusive, meaning never 1.00. If it did, the returned index would be greater than the array length. –  Kelly Sep 16 '13 at 16:32
    
Omg, you're right. –  Denis Gorbachev Sep 17 '13 at 7:25

Only using the array length will result in never actually selecting the last item in the array, except in the extremely rare situation when the random number selected is 1.0000. Better to add .99999 to the arr.length:

var key = Math.floor(Math.random() * (arr.length + .999999))
share|improve this answer
4  
This has the potential to return a number greater than the last index. –  Kelly Sep 16 '13 at 16:34
    
Math.random() Gives a number somewhere from 0 to before 1 (NEVER 1). Written as [0, 1). Also, adding 0.9999999 to the array length causes a possible out of bounds error. Look at the chosen answer –  Steven Rogers Feb 20 at 0:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.