Answers for "javascript function to randomly pick item from an array"

3

javascript get random items from array

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 list
const 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..
Posted by: Guest on February-01-2022
2

get random item from array javascript

const randomElement = array[Math.floor(Math.random() * array.length)];
Posted by: Guest on April-07-2020

Code answers related to "javascript function to randomly pick item from an array"

Code answers related to "Javascript"

Browse Popular Code Answers by Language