How to handle unbiased random selection in Vanilla JS for large arrays #211279
Replies: 3 comments
|
For a tool like this , Math.random() should be fine. With around 100 items, any bias from using Math.floor(Math.random() * array.length) is too small to matter in practice. For picking 20 unique items, I'd just shuffle a copy of the array using Fisher-Yates and take the first 20. const shuffled = [...universities]; const selected = shuffled.slice(0, 20); This avoids duplicates without having to keep generating random indexes. It's also fast enough for arrays much largr than 100 items. I'd only bother with crypto.getRandomValues() if the randomness needs to be unpredictable, like for a prize draw or something security-related. |
|
For this tool, Math.random and the Fisher Yates shuffle suggested above are reasonable. One catch if you switch to crypto: using a random integer For exactly 100 items, draw a Uint32 value, retry if it's 4294967200 or higher, then use |
|
If you only need one random element, you don't need to shuffle the whole array. function pickRandom(items) {
if (items.length === 0) return undefined;
return items[Math.floor(Math.random() * items.length)];
}This is O(1) time and doesn't modify the array. If you need multiple unique random elements, consider a partial Fisher–Yates shuffle. You only perform as many swaps as the number of elements requested, rather than shuffling the entire collection. One important distinction: Also avoid |
Uh oh!
There was an error while loading. Please reload this page.
🏷️ Discussion Type
Question
💬 Feature/Topic Area
Learning Paths
Body
I am currently building a suite of lightweight web tools using only Vanilla JavaScript and HTML. I am trying to avoid heavy frameworks like React to keep the page load speed very fast for users.
I have a question about generating random items from a large array. For example, I built a random college generator that pulls from a list of over 100 universities. You can see the tool in action on my website at randomclickgenerator.com.
Currently, I am using Math.random combined with Math.floor to pick an index from the array.
Is Math.random good enough for a tool like this. Or should I be using crypto.getRandomValues to ensure the selection is completely unbiased. I know Math.random is not cryptographically secure but I am wondering if there is any noticeable bias when selecting from an array of 100 items.
I also want to know the best way to prevent duplicates when generating a list of 20 random items from that array without making the loop too slow.
Any advice or code snippets would be greatly appreciated. Thank you.
All reactions