Suppose I have 16 numbers, range 0 to 15. They sit in an array. What I want to achieve is the following arrays:
The numbers from the, what I will call, masterarray, can only be used once. So array x holds 1, 5 and 7, array y holds 2, 9 (these should be totally random).
I understand that I can get and remove items from an array using indexOf
and splice
. But how would I go about getting the random numbers from the array while also removing them from this list?
A foreach wouldn't go as the array gets altered in this process. Same goes for a for-loop, to my understanding.
How can I achieve this?
here's a non-shuffle approach...
var master = [], arr1=[], arr2=[], arr3=[], arr4=[], arr5=[], arr6=[], i=1;
for(i; i<16;i++){ // populating "master" array
master.push(i);
}
while(master.length>0){
var num =master.splice(Math.floor(Math.random()*master.length),1)[0];
if (master.length>11){
arr1.push(num);
continue;
}
if(master.length>9){
arr2.push(num);
continue;
}
if(master.length>6){
arr3.push(num);
continue;
}
if(master.length>4){
arr4.push(num);
continue;
}
if(master.length>2){
arr5.push(num);
continue;
}
else {
arr6.push(num);
}
}
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
console.log(arr5);
console.log(arr6);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.