var item = items[Math.floor(Math.random()*items.length)];
Answer from Kelly on Stack Overflowvar item = items[Math.floor(Math.random()*items.length)];
1. solution: define Array prototype
Array.prototype.random = function () {
return this[Math.floor((Math.random()*this.length))];
}
that will work on inline arrays
[2,3,5].random()
and of course predefined arrays
var list = [2,3,5]
list.random()
2. solution: define custom function that accepts list and returns element
function get_random (list) {
return list[Math.floor((Math.random()*list.length))];
}
get_random([2,3,5])
javascript - How to get a number of random elements from an array? - Stack Overflow
Selecting a random element from a JavaScript array
How to select multiple elements randomly from an array (without selecting the same thing twice)?
Getting a random value from a JavaScript array - Stack Overflow
Videos
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;
}
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?
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]);
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);
You could shuffle the array and pick the first four.
numbers.sort( function() { return 0.5 - Math.random() } );
Now numbers[0], numbers[1]... and so on have random and unique elements.
Note that this method may not be an optimal way to shuffle an array: see Is it correct to use JavaScript Array.sort() method for shuffling? for discussion.
If you want this to be as random as the native implementations of JavaScript's Math.random() will allow, you could use something like the following, which also has the advantages of leaving the original array untouched and only randomizing as much of the array as required:
function getRandomArrayElements(arr, count) {
var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
var numbers = ['1','2','4','5','6','7','8','9','10'];
alert( getRandomArrayElements(numbers, 4) );