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)
})
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.