Shyam Dixit Shyam Dixit - 4 months ago 14
jQuery Question

How to get n no elements randomly from an array

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 array with jQuery

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


Question: 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.So please just from this statement how can we get more than one elements from an array.

Answer

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