Get random item from JavaScript array [duplicate]

Get random item from JavaScript array [duplicate]

This question already has an answer here:

Getting a random value from a JavaScript array

23 answers

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

How do I get random item from items?

Solutions/Answers:

Solution 1:

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

Solution 2:

If you really must use jQuery to solve this problem:

(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/

Solution 3:

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];

Solution 4:

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

Solution 5:

1. solution: define Array prototype

Array.prototype.random = function () {
  return this[Math.floor((Math.random()*this.length))];
}

that will work on inline arrays

[2,3,5].random()

and of course predefined arrays

list = [2,3,5]
list.random()

2. solution: define custom function that accepts list and returns element

get_random = function (list) {
  return list[Math.floor((Math.random()*list.length))];
} 

get_random([2,3,5])

Solution 6:

Here’s yet another way:

function rand(items) {
    return items[~~(items.length * Math.random())];
}