-1

I have the code to pick something randomly but only for a list of 6 names. What should I add to my code to import from a list of 200 and make sure I don't get the same answer twice?

<div>
    <button onclick="findspeech();" type="randomspeech">Random 
Speech</button>
    <input "randomspeech" id="randomspeech">
  </div>
  
  <script>
  function findspeech() {
      var speech = ["Bednar", "Nelson", "Uchtdorf", "Christofferson", 
"Eyring", "Gong"];
  
      var random = Math.floor(Math.random() * (speech.length - 1));
  
      document.getElementById("randomspeech").setAttribute("value", 
speech[random]);
  }
  
  </script>
  • https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array Shuffle it to start and pop them off. Or random number and remove it once you use it – epascarello Feb 18 '21 at 23:07
  • You should not use setAttribute to set a form value. – epascarello Feb 18 '21 at 23:09

1 Answers1

0

You can shuffle the array and then go through it sequentially.

var speech = ["Bednar", "Nelson", "Uchtdorf", "Christofferson",
    "Eyring", "Gong"
];
//Shuffle
for (let i = speech.length - 1; i > 0; i--) {
    const j = Math.random() * (i + 1) | 0;
    [speech[i], speech[j]] = [speech[j], speech[i]];
}
let idx = 0;

function findspeech() {
    document.getElementById("randomspeech").value = speech[idx++];
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80