There are two kinds of random-selection methods, "roll" and "deal". Roll can get the same value more than once, as in rolling dice. Deal gets a different value, as in dealing cards.
You're using roll. You need deal. You need to remove each value from further consideration as you choose it.
Let's say you've populated your users
array, and now you want to deal num
values from it. To do this you removed each item from your array as you choose it. It's a job for splice()
.
for (let i = 0; i < num; i++) {
if (users.length <= 0) break
const randex = Math.floor(Math.random() * users.length)
const user = users.splice(randex, 1)[0]
/* do what you want with this user */
}
Splice is a good choice for this; the V8 Javascript engine developers worked hard to make it as efficient as possible.
You can test this by pasting the following code into your console REPL in your browser devtools.
(function deal (k, n) {
function range1(i){return i?range1(i-1).concat(i):[]}
const users = range1(n)
for (let i = 0; i < k; i++) {
if (users.length <= 0) break
const randex = Math.floor(Math.random() * users.length)
const user = users.splice(randex, 1)[0]
console.log (user)
}
})(7, 52)
This is a simplification of the Fisher-Yates (aka Knuth) shuffle algorithm mentioned here. That algorithm shuffles everything in the input array. But that's not necessary if you only need to sample a few items from a longer array.