Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 267
Webnet Avatar asked Nov 23 '10 04:11

Webnet


2 Answers

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

var key = Math.floor(Math.random() * arr.length);
like image 195
James Kovacs Avatar answered Oct 20 '22 13:10

James Kovacs


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

like image 43
Adriaan Stander Avatar answered Oct 20 '22 14:10

Adriaan Stander