In my program, when the user clicks a button, an item (a string) from an array gets randomly selected, and is then outputted to the user.
My goal is to introduce some kind of "remove this item from the array after displaying to the user" functionality, to prevent repeat outputs. That way, each time they're viewing a fresh item, and not seeing the same ones over and over again.
Here is my v1 version of coding this:
Array1 = [] // the full array of all items is contained in here.
Array2 = [] // this is the post-display holding bay for items the user has seen already.
After outputting an item to the user from Array 1? That item will be added to Array 2. BEFORE displaying any array items to a user? It will cross-reference the randomly selected item against the full list of items in Array2, basically using IF/ELSE IF logic. Something like this:
for (let i = 0; i < NumberOfArray2Items; i++) {
if (Array1ItemToDisplay === Array2[i]) {
NumberOfMatches = j++ // basically, increment a numerical variable, so that any value
// greater than 0 indicates, yes, it's been outputted to the user before
}
}
if (NumberOfMatches === 0) {
DisplayCurrentArrayItem();
} else if (NumberOfMatches > 0) {
SelectAnotherArrayItemToDisplay();
}
That's a rough version of what I have in mind, and frankly it sounds like a terrible solution because it requires two very lengthy programmatic steps:
- Looping over every single item in Array2 for cross-referencing
- Potentially running that dozens, maybe hundreds of times, if it continues to find matches each time it runs that block of code.
Is there some simpler, faster method of cross-refencing an item against an entire array? Or perhaps cross-referencing both arrays against each other, to only leave the remaining items that don't match, and then select from that intermediate list of items that hasn't yet been displayed?
These arrays will contain tens of thousands of items, so my concern is, as presently written, this code will take forever to execute. Is there some simpler, faster, more efficient solution I'm not seeing?