0

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++; 
AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
  • 1
    1. shuffle the array 2. go in (new) order which is random and non-repeating. [Generating non-repeating random numbers in JS](https://stackoverflow.com/q/18806210) | [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/q/2450954) – VLAZ Apr 08 '21 at 18:46
  • As @VLAZ suggested, just [shuffle](https://javascript.info/task/shuffle) the array and pick the first item. – AbsoluteBeginner Apr 08 '21 at 21:26
  • Anyway, the title of your question is misleading. – AbsoluteBeginner Apr 08 '21 at 21:53

2 Answers2

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++;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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>
Nora
  • 612
  • 3
  • 11