grab random element in array code example
Example 1: Javascript get random item from array
var colors = ["red","blue","green","yellow"];
var randomColor = colors[Math.floor(Math.random()*colors.length)];
Example 2: js get random number from array
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);
Example 3: random item from array javascript
function RandomItemFromArray(myArray) {
return myArray[Math.floor(Math.random() * myArray.length)]
}
var fruit = [ "Apples", "Bananas", "Pears", ];
let fruitSample = RandomItemFromArray(fruit)
Example 4: get random elements from array javascript
array.sort(() => Math.random() - Math.random()).slice(0, n)