Reputation: 15
I'm trying to get a random amount of items from an array.
This is what I've got so far:
I'm calling the function (in another part of a long code) with the min and max values:
generateitems(1,7)
And this is the rest:
function generateitems(min, max) {
var myArray = ["aa","bb","cc","dd","ee","ff","gg"];
var randomItem = myArray[Math.floor(Math.random()* (max - min)) + min];
return randomItem;
}
I keep just getting one item as a result. How do I fix this?
I know how to generate one/a specific amount, or all of the items from the array, and my program works when I do that -- so I don't think there's an issue with the rest of my code. I just can't figure out how to use Math.random here, or if it's even the right thing to use in this case.
Thank you for your time.
EDIT:
wanted result:
the function should return 1-7 items
duplicates are ok, I don't care about the order of the items
Upvotes: 0
Views: 108
Reputation: 386604
You need a loop for getting the wanted items and take the length as factor for getting a random index.
function generateitems(min, max) {
var values = ["aa","bb","cc","dd","ee","ff","gg"],
result = [],
items = Math.floor(Math.random() * (max - min)) + min;
while (items--)
result.push(values[Math.floor(Math.random() * values.length)]);
return result;
}
console.log(generateitems(1, 7));
Upvotes: 1
Reputation: 66123
That's because on this line in your code, you are generating an array with a single entry:
var randomItem = myArray[Math.floor(Math.random()* (max - min)) + min];
If you want to generate a random number of items, you need to:
min
and max
value to generate an array of a random lengthArray.prototype.map
.Note that your original logic is flawed: if you want to select a random element from an array. using myArray[Math.floor(Math.random() * myArray.length]
should work. The min
and max
, as I suspect for your case, is only used to determine the length of the randomly generated array.
function generateitems(min, max) {
var myArray = ["aa","bb","cc","dd","ee","ff","gg"];
var arrayLength = Math.floor(Math.random()* (max - min)) + min
return [...new Array(arrayLength)].map(function() {
return myArray[Math.floor(Math.random()* myArray.length)];
});
}
console.log(generateitems(1,7));
This however, does not generate an array that is unique, because you are basically selecting items from an array at random (which means that is a chance of value collision).
If you want to create a shuffled/randomized subset of an existing array, then this answer will suit your needs the best: Sampling a random subset from an array
Upvotes: 4