0

I'm trying to create an array of 12 unique products. These products are being selected from a list of products that are retrieved from my MONGODB Database. I can create the array quite alright, but I can't seem to get the length of the array to be 12 every time. I need the minimum length of the array to be 12 and the maximum length of the array to also be 12.

This is my code below and everytime I run this code, randomProducts.length is usually a random length, instead of 12.


Products.find({}).limit(12).exec(function (err, randProducts) {
    var randomProducts = []
    for (let i = 0; i < randProducts.length; i++) {
      var rand = Math.floor(Math.random() * (randProducts.length - 0) + 0);
      if (randomProducts.includes(randProducts[rand]) == false) {
        randomProducts.push(randProducts[rand])
      }
    }
    console.log(randomProducts.length)
})
  • 1
    Does the store contain duplicates? Or are you just trying to get 12 products (that you already know aren't duplicated) and shuffle them? *(I guess the objects will be distinct regardless, but...)* – T.J. Crowder Jan 12 '22 at 13:08
  • The store doesn't contain duplicates. All the items are unique. However, since I'm generating a random set of products from 0 to randProducts.length, there is the likelihood that a product may be repeated in the randomProducts array. I wouldn't want a product to appear twice in the array. – Awesome Bassey Jan 12 '22 at 13:36
  • That being the case, you're [shuffling an array](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array). – T.J. Crowder Jan 12 '22 at 13:41

1 Answers1

0

You are starting with an initial set of 12 products due to the .limit(12) call of your MongoDB query.

Selecting 12 random elements from a set of 12 elements is also called shuffling or randomizing the array. Shuffling an array has been explained multiple times: How to randomize (shuffle) a JavaScript array?

For picking 12 random elements from a larger array have a look here: How to get a number of random elements from an array?

Your code has the problem that you are trying 12 times to pick a random product. But if the product already is picked (which it will be in a lot of cases) you do nothing. So you'd have to get pretty lucky to get all 12 products in a random order.

Benno
  • 968
  • 6
  • 15
  • Thank you. I've found the answer in the link you specified at [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/19269545/how-to-get-a-number-of-random-elements-from-an-array). I could have searched the whole internet and still wouldn't have stumbled upon this answer. Thank you. – Awesome Bassey Jan 12 '22 at 13:45