[javascript] Getting a random value from a JavaScript array

Consider:

var myArray = ['January', 'February', 'March'];    

How can I select a random value from this array using JavaScript?

This question is related to javascript random

The answer is


Create one random value and pass to array

Please try following code..

//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];

alert(Placeholdervalue);

Prototype Method

If you plan on getting a random value a lot, you might want to define a function for it.

First, put this in your code somewhere:

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

Now:

[1,2,3,4].sample() //=> a random element

Code released into the public domain under the terms of the CC0 1.0 license.


If you have fixed values (like a month name list) and want a one-line solution

var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]

The second part of the array is an access operation as described in Why does [5,6,8,7][1,2] = 8 in JavaScript?


In my opinion, better than messing around with prototypes , or declaring it just in time, I prefer exposing it to window:

window.choice = function() {
  if (!this.length || this.length == 0) return;
  if (this.length == 1) return this[0];
  return this[Math.floor(Math.random()*this.length)];
}

Now anywhere on your app you call it like:

var rand = window.choice.call(array)

This way you can still use for(x in array) loop properly


By adding a method on prototype of array you can get random values easly.

In this example you can get single or multiple random values from array.

You can run to test code by clicking snippet button.

_x000D_
_x000D_
Array.prototype.random = function(n){
  if(n&&n>1){
    const a = [];
    for(let i = 0;i<n;i++){
      a.push(this[Math.floor(Math.random()*this.length)]);
    }
    return a;
  } else {
    return this[Math.floor(Math.random()*this.length)];
  }
}

const mySampleArray =  ['a','b','c','d','e','f','g','h'];

mySampleArray.random(); // return any random value etc. 'a', 'b'
mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d']

alert(mySampleArray.random());
alert(mySampleArray.random(3));
_x000D_
_x000D_
_x000D_


To get crypto-strong random item form array use

_x000D_
_x000D_
let rndItem = a=> a[rnd()*a.length|0];_x000D_
let rnd = ()=> crypto.getRandomValues(new Uint32Array(1))[0]/2**32;_x000D_
_x000D_
var myArray = ['January', 'February', 'March'];_x000D_
_x000D_
console.log( rndItem(myArray) )
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
static generateMonth() { _x000D_
const theDate = ['January', 'February', 'March']; _x000D_
const randomNumber = Math.floor(Math.random()*3);_x000D_
return theDate[randomNumber];_x000D_
};
_x000D_
_x000D_
_x000D_

You set a constant variable to the array, you then have another constant that chooses randomly between the three objects in the array and then the function simply returns the results.


Say you want to choose a random item that is different from the last time (not really random, but still a common requirement)...

/**
 * Return a random element from an array that is
 * different than `last` (as long as the array has > 1 items). 
 * Return null if the array is empty.
*/
function getRandomDifferent(arr, last = undefined) {
  if (arr.length === 0) {
    return;
  } else if (arr.length === 1) {
    return arr[0];
  } else {
    let num = 0;
    do {
      num = Math.floor(Math.random() * arr.length);
    } while (arr[num] === last);
    return arr[num];
  }
}

Implement like this:

const arr = [1,2,3];
const r1 = getRandomDifferent(arr);
const r2 = getRandomDifferent(arr, r1); // r2 is different than r1.

If you've already got underscore or lodash included in your project you can use _.sample.

// will return one item randomly from the array
_.sample(['January', 'February', 'March']);

If you need to get more than one item randomly, you can pass that as a second argument in underscore:

// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);

or use the _.sampleSize method in lodash:

// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);

randojs makes this a little more simple and readable:

_x000D_
_x000D_
console.log( rando(['January', 'February', 'March']).value );
_x000D_
<script src="https://randojs.com/1.0.0.js"></script>
_x000D_
_x000D_
_x000D_


A generic way to get random element(s):

_x000D_
_x000D_
let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];_x000D_
let months = random_elems(some_array, 3);_x000D_
_x000D_
console.log(months);_x000D_
_x000D_
function random_elems(arr, count) {_x000D_
  let len = arr.length;_x000D_
  let lookup = {};_x000D_
  let tmp = [];_x000D_
_x000D_
  if (count > len)_x000D_
    count = len;_x000D_
_x000D_
  for (let i = 0; i < count; i++) {_x000D_
    let index;_x000D_
    do {_x000D_
      index = ~~(Math.random() * len);_x000D_
    } while (index in lookup);_x000D_
    lookup[index] = null;_x000D_
    tmp.push(arr[index]);_x000D_
  }_x000D_
_x000D_
  return tmp;_x000D_
}
_x000D_
_x000D_
_x000D_


Editing Array prototype can be harmful. Here it is a simple function to do the job.

function getArrayRandomElement (arr) {
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
  // The undefined will be returned if the empty array was passed
}

Usage:

// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);

Faker.js has many utility functions for generating random test data. It is a good option in the context of a test suite:

const Faker = require('faker');
Faker.random.arrayElement(['January', 'February', 'March']);

As commenters have mentioned, you generally should not use this library in production code.


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

or equivalent shorter version:

var item = myArray[(Math.random()*myArray.length)|0];

Sample code:

_x000D_
_x000D_
var myArray = ['January', 'February', 'March'];    _x000D_
var item = myArray[(Math.random()*myArray.length)|0];_x000D_
console.log('item:', item);
_x000D_
_x000D_
_x000D_


I've found a way around the top answer's complications, just by concatenating the variable rand to another variable that allows that number to be displayed inside the calling of myArray[];. By deleting the new array created and toying around with it's complications, I've come up with a working solution:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>

var myArray = ['January', 'February', 'March', 'April', 'May'];    

var rand = Math.floor(Math.random() * myArray.length);

var concat = myArray[rand];

function random() {
   document.getElementById("demo").innerHTML = (concat);
}
</script>

<button onClick="random();">
Working Random Array generator
</button>

</body>
</html>

Here is an example of how to do it:

$scope.ctx.skills = data.result.skills;
    $scope.praiseTextArray = [
    "Hooray",
    "You\'re ready to move to a new skill", 
    "Yahoo! You completed a problem", 
    "You\'re doing great",  
    "You succeeded", 
    "That was a brave effort trying new problems", 
    "Your brain was working hard",
    "All your hard work is paying off",
    "Very nice job!, Let\'s see what you can do next",
    "Well done",
    "That was excellent work",
    "Awesome job",
    "You must feel good about doing such a great job",
    "Right on",
    "Great thinking",
    "Wonderful work",
    "You were right on top of that one",
    "Beautiful job",
    "Way to go",
    "Sensational effort"
  ];

  $scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];

Simple Function :

var myArray = ['January', 'February', 'March'];
function random(array) {
     return array[Math.floor(Math.random() * array.length)]
}
random(myArray);

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

Recursive, standalone function which can return any number of items (identical to lodash.sampleSize):

function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}

This is similar to, but more general than, @Jacob Relkin's solution:

This is ES2015:

const randomChoice = arr => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
};

The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.


The shortest version:

var myArray = ['January', 'February', 'March']; 
var rand = myArray[(Math.random() * myArray.length) | 0]

If you want to write it on one line, like Pascual's solution, another solution would be to write it using ES6's find function (based on the fact, that the probability of randomly selecting one out of n items is 1/n):

_x000D_
_x000D_
var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));_x000D_
console.log(item);
_x000D_
_x000D_
_x000D_

Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers (floor(random()*length and using a seperate function) are your way to go.


Looking for a true one-liner I came to this:

['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })

~~ is much faster than Math.Floor(), so when it comes to performance optimization while producing output using UI elements, ~~ wins the game. MORE INFO

var rand = myArray[~~(Math.random() * myArray.length)];

But if you know that the array is going to have millions of elements than you might want to reconsider between Bitwise Operator and Math.Floor(), as bitwise operator behave weirdly with large numbers. See below example explained with the output. MORE INFO(deadlink)

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343