// Shuffle arrayconst shuffled = array.sort(()=>0.5-Math.random());// Get sub-array of first n elements after shuffledlet selected = shuffled.slice(0, n);
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 */
let fruits =["Apple","Banana","Mango","Orange"];// arraylet index =Math.floor(Math.random()* fruits.length);// random indexconsole.log(fruits[index]);// result
const array =[1,2,3,4,5,6,7,8,9];const string ="abcdefghijklmnopqrstuvwxyz";// random item from Arrayconsole.log(array[Math.floor(Math.random()* array.length)]);// random Char from Stringconsole.log(string[Math.floor(Math.random()* string.length)]);
const list =[1,2,3,4,5,6];// shuffle your list with the sort function:const shuffledList = list.sort(()=>Math.random()-0.5);// generate a size for the new listconst newListSize =Math.floor(Math.random()* list.length)// pick the first "newListSize" elements from "shuffledList"const newList = shuffledList.slice(0, newListSize)console.log(newList);// [3, 2, 6]; [5]; [4, 1, 2, 6, 3, 5]; []; etc..
// how to generate random words from an arrayconstCoins=["Heads","Tails"]letGenerate=Math.floor((Math.random()*Coins.length));console.log(Coins[Generate])// this will print the outcome
//Make all arrays have "random" methodArray.prototype.random=function(){returnthis[Math.floor(Math.random()*this.length)];}//Call "random" method on an arrayvar result =["Hello","world"].random();
how to get a random statement from an array in javascript
// List your array itemsletTesting1=["put","things","here"]letGenerate=Math.floor((Math.random()*Testing1.length));// Generates a number of the array.// logs the resultconsole.log(Testing1[Generate])
// Define random() method of ArraysArray.prototype.random=function(){returnthis[Math.floor(Math.random()*this.length)];}console.log([1,2,3,4,5,6].random());// 5 for exampleconsole.log(['apple','banana','orange'].random());// 'orange' for example