Remove an Option From a Random Selection Array in JavaScript
I'm working on a site for Weird Web October. The idea runs on an infinite loop where each iteration picks a random item from an array of possibilities. But, I don't want the same item picked twice in a row.
This is the function I'm using to make that happen.
It takes an array and an item. If the item is in the array, then a new array is generated with the item removed. The new item is picked randomly from that array.
If the item isn't in the list, the new item is picked from the entirety of the original array.
Multi Item Example
Here's the function in action with an array of five items.
Output
HTML
Update From Five Items
waiting
window. =
Just Two Items
And to give a tighter demo, here's an array with two items. Because, the function won't return the same item twice in a row, clicking the button effectively toggles between them.
Output
HTML
Update From Two Items
waiting
window. =
Endnotes
Note that the this. isn't defined before the first time it's sent to the function in the examples. This isn't a problem since an explicit check is done to see if the item is in the array.
I'm using bitty for the examples. It's the web component that wires up the signals between the HTML and JavaScript. Check it out if you're into that kinda thing.