how to generate random amount of items from an array

coldshoulders :

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

Terry :

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:

  1. Use the min and max value to generate an array of a random length
  2. After the array is generated, you then push a random item into it using Array.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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=279064&siteId=1