Q:

how to get a random statement from an array in javascript

//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
var item = items[Math.floor(Math.random() * items.length)];
1
array.sort(() => Math.random() - Math.random()).slice(0, n)
0
// List your array items
let Testing1 = ["put","things","here"]
let Generate = Math.floor((Math.random() * Testing1.length)); // Generates a number of the array.

// logs the result
console.log(Testing1[Generate])
0
 const arr = myArray
      .map((a) => ({sort: Math.random(), value: a}))
      .sort((a, b) => a.sort - b.sort)
      .map((a) => a.value)
0

New to Communities?

Join the community