I'm looking to make a list item randomizer that only displays that item once. I have a basic randomizer working that pulls from an array, but when I click the button, it just continues to loop through each item. Is there a way to get each item it only display once then stop and/or display something like "list over" once complete? My js skills are very basic...
The js randomizer code:
var techniques = [
"item 1",
"item 2",
"item 3",
"item 4",
"item 5"
]
function newTechnique() {
var randomNumber = Math.floor(Math.random() * (techniques.length));
document.getElementById('techDisplay').innerHTML = techniques[randomNumber];
}
and the html
<div id="techDisplay"></div>
<button onclick="newTechnique()">New Technique</button>
I'm also wondering if there is a better way to pull in data, like using an xml or something? I intend to have likely over 50 items in the list, which could become cumbersome in the js. Let me know and thanks in advance!
Here is the code for the functionality you are looking for
const techniques = [
'Currently showing item 1',
'Currently showing item 2',
'Currently showing item 3',
'Currently showing item 4',
'Currently showing item 5',
'Currently showing item 6'
];
let flags = techniques.map(() => false);
function getNotShownNumber() {
let whichItemToShow;
const allAreTrue = flags.every((v) => v === true);
if (!allAreTrue) {
let value = true;
do {
const randomNumber = Math.floor(Math.random() * techniques.length);
const alreadyShown = flags[randomNumber];
if (!alreadyShown) {
flags[randomNumber] = true;
whichItemToShow = randomNumber;
value = false;
}
} while (value);
} else {
whichItemToShow = 'Completed';
}
return whichItemToShow;
}
function newTechnique() {
const number = getNotShownNumber();
const content =
number === 'Completed' ? 'List Over' : techniques[number];
document.getElementById('techDisplay').innerHTML = content;
}
<div id="techDisplay"></div>
<button onclick="newTechnique()">New Technique</button>