0
Q:

javascript how to get a random element from an array

//get random value from array
var colors = ["red","blue","green","yellow"];
var randColor = colors[Math.floor(Math.random() * colors.length)];
14
var colors = ["red","blue","green","yellow"];
var randomColor = colors[Math.floor(Math.random()*colors.length)]; //pluck a random color
9
var items = ['Yes', 'No', 'Maybe'];
var item = items[Math.floor(Math.random() * items.length)];
13
var myArray = [
  "Apples",
  "Bananas",
  "Pears"
];

var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
9
var foodItems = ["Bannana", "Apple", "Orange"];
var theFood = foodItems[Math.floor(Math.random() * foodItems.length)];
/* Will pick a random number from the length of the array and will go to the
corosponding number in the array E.G: 0 = Bannana */
6
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const randomMonth = months[Math.floor(Math.random() * months.length)];

console.log("random month =>", randomMonth);
7
const randomElement = array[Math.floor(Math.random() * array.length)];
5
var item = items[Math.floor(Math.random() * items.length)];
1
let items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];

let  randomItem = items[Math.floor(Math.random() * items.length)];
0
array.sort(() => Math.random() - Math.random()).slice(0, n)
0

New to Communities?

Join the community