1

I have an array storing a bunch of questions, I'm trying to randomly pick a question and display it, it's working but I don't want a question to appear more than once, this is what I'm trying but it's not working:

 // Randomely pick a question from the array randomItem = questions[Math.floor(Math.random()*questions.length)]; questions.splice(randomItem); random = document.getElementById('questions'); random.innerText = randomItem; counter++; 
3

2 Answers 2

1

You need to take the index instead of teh value of the array. Then splice with that index and get the item of the array.

const index = Math.floor(Math.random() * questions.length), randomItem = questions.splice(index, 1)[0]; random = document.getElementById('questions'); random.innerText = randomItem; counter++; 
0
    0

    You have to spare the index of the random question and then remove that index from the array before continuing to the next question, until the array runs out of elements and there's no more questions left.

    This way once a question has been asked, it's no longer in the array and it cannot be asked again. It's important you spare the question before removing it from the array, otherwise you'll be left empty handed.

    const element = document.getElementById("question"); const questions = [ "Is earth flat?", "Is earth an orange?", "Is earth a lemon?" ]; const interval = setInterval(function() { if(questions.length == 0) { element.innerText = "There's no more questions!"; clearInterval(interval); return; } const index = Math.floor(Math.random() * questions.length); element.innerText = questions[index]; questions.splice(index, 1); }, 1000);
    <div id="question"></div>

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.