Get a random item from a JavaScript array

JavascriptArraysRandom

Javascript Problem Overview


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

How do I get random item from items?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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 3 - Javascript

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

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

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

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


get_random([2,3,5])

Solution 4 - Javascript

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/

Solution 5 - Javascript

Here's yet another way:

function rand(items) {
    // "~~" for a closest "int"
    return items[~~(items.length * Math.random())];
}

Or as recommended below by @1248177:

function rand(items) {
    // "|" for a kinda "int div"
    return items[items.length * Math.random() | 0];
}

Solution 6 - Javascript

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

Solution 7 - Javascript

jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,

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

Solution 8 - Javascript

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

Solution 9 - Javascript

// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})

// 2. Get first item
var item = items[0]

Shorter:

var item = items.sort(function() {return 0.5 - Math.random()})[0];

Even shoter (by José dB.):

let item = items.sort(() => 0.5 - Math.random())[0];

Solution 10 - Javascript

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

function rand(min, max) {
  var offset = min;
  var range = (max - min) + 1;
 
  var randomNumber = Math.floor( Math.random() * range) + offset;
  return randomNumber;
}


randomNumber = rand(0, items.length - 1);

randomItem = items[randomNumber];

credit:

Javascript Function: Random Number Generator

Solution 11 - Javascript

If you are using node.js, you can use unique-random-array. It simply picks something random from an array.

Solution 12 - Javascript

An alternate way would be to add a method to the Array prototype:

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

 var teams = ['patriots', 'colts', 'jets', 'texans', 'ravens', 'broncos']
 var chosen_team = teams.random(teams.length)
 alert(chosen_team)

Solution 13 - Javascript

const ArrayRandomModule = {
  // get random item from array
  random: function (array) {
    return array[Math.random() * array.length | 0];
  },

  // [mutate]: extract from given array a random item
  pick: function (array, i) {
    return array.splice(i >= 0 ? i : Math.random() * array.length | 0, 1)[0];
  },

  // [mutate]: shuffle the given array
  shuffle: function (array) {
    for (var i = array.length; i > 0; --i)
      array.push(array.splice(Math.random() * i | 0, 1)[0]);
    return array;
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamesView Question on Stackoverflow
Solution 1 - JavascriptKellyView Answer on Stackoverflow
Solution 2 - JavascriptchimView Answer on Stackoverflow
Solution 3 - JavascriptDino ReicView Answer on Stackoverflow
Solution 4 - JavascriptAlnitakView Answer on Stackoverflow
Solution 5 - JavascriptK-GunView Answer on Stackoverflow
Solution 6 - JavascriptRocket HazmatView Answer on Stackoverflow
Solution 7 - JavascriptplanetjonesView Answer on Stackoverflow
Solution 8 - JavascriptBlindyView Answer on Stackoverflow
Solution 9 - JavascriptIvan PirogView Answer on Stackoverflow
Solution 10 - JavascriptneebzView Answer on Stackoverflow
Solution 11 - JavascriptAayan LView Answer on Stackoverflow
Solution 12 - JavascriptJames DalyView Answer on Stackoverflow
Solution 13 - JavascriptNicolasView Answer on Stackoverflow