js get random in array 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: random string from array javascript

var textArray = [
    'song1.ogg',
    'song2.ogg'
];
var randomNumber = Math.floor(Math.random()*textArray.length);

Example 3: get random element from array js

var item = items[Math.floor(Math.random() * items.length)];

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