Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Get a random item from a JavaScript array

var items = Array(523, 3452, 334, 31, ..., 5346);


How would I get an irregular item from items?
by

2 Answers

akshay1995

var item = items[Math.floor(Math.random() * items.length)];
kshitijrana14
Use underscore (or loDash :)):
var randomArray = [
'#cc0000','#00cc00', '#0000cc'
];

// use _.sample
var randomElement = _.sample(randomArray);

// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];

Or to shuffle an entire array:

// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];

Login / Signup to Answer the Question.