I want to have an array with different words and phrases and randomly generate around five of these on page refresh. How would I go about doing this in javascript?
Asked
Active
Viewed 3,817 times
-1
-
4http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array – Andy Jan 12 '16 at 10:44
-
Where are you stuck? Do you not know how to generate a random number from 0-n? Do you know know how to loop to get five of them? Do you not know how to get the element from the array once you have a random index? – Jan 12 '16 at 12:02
2 Answers
0
You could use the array length and run a for loop to do this with Math.random():
var randomNums = [];
for(var i=0; i<5; i++){
int x = myArray[Math.random()*(myArray.length-1)];
if(!randomNums.contains(x)){
randomNums.push(x);
}
}
randomNums should then be an array with five random values from your other array

NiallMitch14
- 1,198
- 1
- 12
- 28
0
Run through a loop.
Each time remove 1 object from your original array and put it into a new one
If you want to keep your original array, you can make a copy.
var myArray = [];
var myNewArray = [];
for (var i=0; i<5; i++) {
myNewArray.push(myArray.splice(Math.random()*(myArray.length-1),1).pop());
}
You could also create an array with 5 random numbers between 0 and myArray.length-1. Then you have to check after each random number generation, if the generated number is already in the array.
var indexArr = [];
while (indexArr.length < 5) {
var rndIndex = Math.random()*(myArray.length-1);
if (indexArr.indexOf(rndIndex) == -1) // if rndIndex is not in indexArr
indexArr.push(rndIndex);
}
Then you can use the indexArray to return 5 random elements from your original array.

Flikk
- 520
- 3
- 10