Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  125] [ 1]  / answers: 1 / hits: 176534  / 11 Years ago, wed, october 9, 2013, 12:00:00

I am working on 'how to access elements randomly from an array in javascript'. I found many links regarding this. Like:
Get random item from JavaScript array


var item = items[Math.floor(Math.random()*items.length)];

But in this, we can choose only one item from the array. If we want more than one elements then how can we achieve this? How can we get more than one element from an array?


More From » jquery

 Answers
3

Try this non-destructive (and fast) function:


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;
}

[#75122] Tuesday, October 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
;