9

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?

0

3 Answers 3

21

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

var key = Math.floor(Math.random() * arr.length);
Sign up to request clarification or add additional context in comments.

1 Comment

@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.
2

Have a look at JavaScript random() Method and Generating a random number in JavaScript

Comments

-18

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))

2 Comments

This has the potential to return a number greater than the last index.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.