If you shuffle the array and concatenate the number of elements you want to return, the return value will contain as many elements as it can if you request more elements than in the array. You can shuffle the actual array or copy using slice ().
Array.prototype.getRandom= function(num, cut){ var A= cut? this:this.slice(0); A.sort(function(){ return .5-Math.random(); }); return A.splice(0, num); } var a1= [1, 2, 3, 4, 5]; a1.getRandom(2) >>[4, 2]
If you want to remove the selected elements from the original array, so that the second call will not include the elements returned by the first call, pass the second argument: getRandom (3, true);
window.Memry=window.Memry || {}; Memry.a1= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; Memry.a1.getRandom(3,true); >>[5,10,7] Memry.a1.getRandom(3,true); >>[3,9,6] Memry.a1.getRandom(3,true); >>[8,4,1] Memry.a1.getRandom(3,true); >>[2]
kennebec
source share