Coder Perfect

Using a JavaScript array to generate a random value



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

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

Asked by Sarah

Solution #1

It’s a straightforward one-liner:

const randomElement = array[Math.floor(Math.random() * array.length)];

For example:

Answered by Jacob Relkin

Solution #2

You can use _.sample if you already have underscore or lodash in your project.

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

If you need to acquire more than one object at random, you can provide underscore as a second argument:

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

or use the lodash _.sampleSize method:

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

Answered by Brendan Nee

Solution #3

Consider creating a method [].sample() that returns a random element by declaring a function on the Array prototype.

To begin, add the following code to your code to define the prototype function:

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

Later, simply call.sample() to sample a random element from the array:

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

Under the provisions of the CC0 1.0 license, I’m releasing these code snippets into the public domain.

Answered by Ben Aubin

Solution #4

When it comes to performance optimization when producing output using UI components, is significantly faster than Math.Floor(). ADDITIONAL INFORMATION

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

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

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

Answered by Ankur Soni

Solution #5

Let’s say you want to pick a random thing that isn’t the same as 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) {
  } 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.

Answered by CrazyTim

Post is based on