It's a simple one-liner:
const randomElement = array[Math.floor(Math.random() * array.length)];
For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
Answer from Jacob Relkin on Stack OverflowIt's a simple one-liner:
const randomElement = array[Math.floor(Math.random() * array.length)];
For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
If you've already got underscore or lodash included in your project you can use _.sample.
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
If you need to get more than one item randomly, you can pass that as a second argument in underscore:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
or use the _.sampleSize method in lodash:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
javascript - How to get a number of random elements from an array? - Stack Overflow
Pick two random items from an array
Selecting a random element from a JavaScript array
Selecting a random object from an array
Videos
EDIT BELOW
I created an array consisting of foods, for example 'apple', 'banana', 'orange', 'cherry' etc. Now I need something to randomly select 3 elements from this array, without selecting the same thing twice (for example not 'orange' 'orange' 'banana'). I have searched for a solution myself, but I'm fairly new to coding and don't really understand everything. Can someone help me a little bit?
EDIT: I think I found a way using
const randomSelectionH = (n) => {
let newArr = [];
if (n >= healthy_foods.length) {
return healthy_foods;
}
for (let i = 0; i < n; i++) {
let newElem = healthy_foods[Math.floor(Math.random() * healthy_foods.length)];
while (newArr.includes(newElem)) {
newElem = healthy_foods[Math.floor(Math.random() * healthy_foods.length)];
}
newArr.push(newElem);
}
return newArr;
}But now, I need to use this to put the random selection into a html-button-response
I used:
var trial_two_choices = {
type: 'html-button-response',
stimulus: '<p>What food</p>',
choices: [randomSelectionH]
}But this returned an error. trying to make a variable out of the randomSelectionH and putting that as choices didn't resolve the issue. Any idea on what to do?
FYI inefficient and biased algo, read more https://stackoverflow.com/a/18650169/1325646
Just two lines :
// 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);
DEMO:
n = 5;
array = Array.from({ length: 50 }, (v, k) => k * 10); // [0,10,20,30,...,490]
var shuffled = array.sort(function(){ return 0.5 - Math.random() });
var selected = shuffled.slice(0,n);
document.querySelector('#out').textContent = selected.toString();
[<span id="out"></span>]
Try this non-destructive (and fast) function, which does a (partial) Fisher–Yates shuffle until it got n elements:
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}