Ben
Ben

Reputation: 62504

Randomly selecting javascript array key

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?

Upvotes: 9

Views: 9654

Answers (3)

kujo76
kujo76

Reputation: 1

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

Upvotes: -18

James Kovacs
James Kovacs

Reputation: 11661

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

var key = Math.floor(Math.random() * arr.length);

Upvotes: 21

Related Questions