Answers for "how to return 4 random elements from array javascript"

49

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)];
Posted by: Guest on July-31-2019
0

javascript get n random elements from array

// Shuffle array
const shuffled = array.sort(() => 0.5 - Math.random());

// Get sub-array of first n elements after shuffled
let selected = shuffled.slice(0, n);
Posted by: Guest on February-07-2021

Code answers related to "how to return 4 random elements from array javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language