I have a set of users and products that I need to distribute, for example:
The number of values in the array can vary each time - it could be one value one time and three values another time.
It is important that each user receives a unique product with no duplicates.
Currently, my code shuffles the array and assigns ten random products to each user:
var users = ["user1", "user2", "user3"];
var products = ["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9", "p10","p11", "p12", "p13", "p14", "p15", "p16", "p17", "p18", "p19", "p20", "p21", "p22", "p23", "p24", "p25", "p26", "p27", "p28", "p29", "p30"];
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 != currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
i = 0;
while (i < users.length) {
newArray = (shuffle(products)).slice(0, 10)
console.log(users[i++] + ' products: ' + newArray);
}
Output:
user1 products: p5,p6,p13,p2,p19,p22,p8,p20,p27,p28
user2 products: p6,p30,p22,p9,p25,p2,p7,p17,p19,p10
user3 products: p20,p25,p23,p4,p28,p9,p12,p14,p21,p17