There are 2 ways of doing what you want which i can think of
- Shuffle the array and print questions one by one till the end of the array
- Print random questions and removing them from the array
Shuffling the array
You can shuffle the array using differents methods and i've followed this stack overflow answer to do it which look the simplest
You can then remove each time the first question using the js shift
method which remove the first element from an array and returns it
var btnNext = document.getElementById("next");
words = [{
question: "HTML stands for",
answer: "HyperText Markup Language"
},
{
question: "What is a href?",
answer: "Link location attribute"
},
{
question: "What is extensions used to save HTML pages?",
answer: ".html"
}
]
const randomWords = words.sort(() => Math.random() - 0.5);
btnNext.addEventListener('click', function() {
if (randomWords.length > 0) {
const question = randomWords.shift()
document.getElementById("question").innerHTML = question.question;
}
});
<div id="question">
<h3>Questions</h3>
</div>
<button id="next">Next</button>
Printing random question
The second way works with the js splice
function which remove elements from an array and return the removed elements (documentation here)
Printing question
To print question you can then access the function using the slice
method :
const question = words.splice(index, 1)[0] // taking the first element because slice return an array
and then printing it using InnerHTML as you did
document.getElementById("question").innerHTML = question.question;
var btnNext = document.getElementById("next");
words = [{
question: "HTML stands for",
answer: "HyperText Markup Language"
},
{
question: "What is a href?",
answer: "Link location attribute"
},
{
question: "What is extensions used to save HTML pages?",
answer: ".html"
}
]
btnNext.addEventListener('click', function() {
if (words.length > 0) {
var tempWords = [];
if (tempWords.length === 0) {
for (var i = 0; i < words.length; i++) {
tempWords.push(i);
}
}
let index = Math.floor(Math.random() * tempWords.length);
const question = words.splice(index, 1)[0]
document.getElementById("question").innerHTML = question.question;
}
});
<div id="question">
<h3>Questions</h3>
</div>
<button id="next">Next</button>