Get a random item from a JavaScript array [duplicate] Get a random item from a JavaScript array [duplicate] arrays arrays

Get a random item from a JavaScript array [duplicate]


var item = items[Math.floor(Math.random()*items.length)];


Use underscore (or loDash :)):

var randomArray = [   '#cc0000','#00cc00', '#0000cc'];// use _.samplevar randomElement = _.sample(randomArray);// manually use _.randomvar randomElement = randomArray[_.random(randomArray.length-1)];

Or to shuffle an entire array:

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


If you really must use jQuery to solve this problem (NB: you shouldn't):

(function($) {    $.rand = function(arg) {        if ($.isArray(arg)) {            return arg[$.rand(arg.length)];        } else if (typeof arg === "number") {            return Math.floor(Math.random() * arg);        } else {            return 4;  // chosen by fair dice roll        }    };})(jQuery);var items = [523, 3452, 334, 31, ..., 5346];var item = jQuery.rand(items);

This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!

For extra fun, the array return is generated by calling the function recursively based on the array's length :)

Working demo at http://jsfiddle.net/2eyQX/