Reputation: 113
I have a 20 number array. Now I pick (randomly) 5 of these and i wanna put them into another empty array. How can I do? And also, how can I hide them from the first array when they're displayed? Thank you all.
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var randomNumbers = document.getElementById("demo");
randomNumbers.innerHTML = tenNumbers[Math.floor(Math.random()*tenNumbers.length)];
Upvotes: 2
Views: 2676
Reputation: 13676
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var randNums = [];
var randomNumbers = document.getElementById("demo");
for(var i = 0; i < 5; i++)
{
var index = getRandomInt(0, tenNumbers.length - 1);
randNums.push(tenNumbers[index]);
randomNumbers.innerHTML += tenNumbers[index] + ", ";
tenNumbers.splice(index, 1);
}
<div id="demo">
</div>
Upvotes: 0
Reputation: 36965
You could also pick 5 random elements and move them to a new array using .sort
& .splice
one-liner:
var outArray = tenNumbers.sort(function(){ return Math.random() - 0.5; }).splice(0,5);
Upvotes: 0
Reputation: 13304
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var randomNumbersArray = [];
for (var i = 0; i < 5; i++)
{
randomNumbersArray.push(tenNumbers.splice(Math.floor(Math.random()*tenNumbers.length), 1));
}
document.getElementById("random").innerHTML = randomNumbersArray.join("<br />");
<div id="random"></div>
This should do it.
Upvotes: 2
Reputation: 78545
Seems like you should be able to use splice to remove a random element from the original array, then push that result onto a new array:
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var outArray = [];
for(var i=0; i<5; i++) {
outArray.push(tenNumbers.splice(Math.floor(Math.random()*tenNumbers.length), 1)[0]);
}
document.write(outArray + "<br />" + tenNumbers);
Upvotes: 4