selecting random elements from an array code example

Example 1: javascript how to get a random element from an array

var items = ['Yes', 'No', 'Maybe'];
var item = items[Math.floor(Math.random() * items.length)];

Example 2: how to get random item from an array

//Function to make it easier
Array.prototype.random = function() {
    return this[Math.floor((Math.random() * this.length))];
};

var colors = ["red","blue","green","yellow"];
var randomColor = colors.random();

Example 3: get random elements from array javascript

const arr = myArray
      .map((a) => ({sort: Math.random(), value: a}))
      .sort((a, b) => a.sort - b.sort)
      .map((a) => a.value)

Tags:

Misc Example