js random array range code example
Example 1: generate random number array javascript from principal array
let numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
generated = [];
for (let i = 0; i < 10; i++)
{
let random_index;
while(!random_index)
{
let tmp = Math.floor(Math.random() * numbers.length);
if( !generated.filter( (g) => numbers[tmp] == g).length )
random_index = tmp;
}
generated.push(numbers[random_index]);
}
console.log(generated);
Example 2: javascript generate random array
for (var a=[],i=0;i<40;++i) a[i]=i;
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
a = shuffle(a);