choose random item from array javascript code example

Example 1: javascript get random array value

//get random value from array
var colors = ["red","blue","green","yellow"];
var randColor = colors[Math.floor(Math.random() * colors.length)];

Example 2: how to get a random element of an array javascript

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 */

Example 3: pick a random element from an array javascript

var myArray = [
  "Apples",
  "Bananas",
  "Pears"
];

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

Example 4: how to get a randome element from a list in javascript

let numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let randomElem = numList[Math.floor(Math.random() * numList.length)];
console.log(randomElem);

Example 5: 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)