0

I have this function I'm using to display a character and quote from a json file onto my page, but it will occasionally repeat a quote before running through all the items. How can I prevent it from repeating?

const kaneki = document.querySelector("#kaneki-button");
    if (kaneki) {
        kaneki.addEventListener("click", function () {
        fetch("json/ghoul.json")
        .then((response) => response.json())
        .then((response) => { 
        console.log(response);
        let animeData = response[Math.floor(Math.random() * response.length)];
        document.getElementById("quote").innerHTML = animeData.quote;
        document.getElementById("character").innerHTML = animeData.character;
        });
    });
    }
VLAZ
  • 26,331
  • 9
  • 49
  • 67
preston17
  • 19
  • 5
  • 1
    The classic way to do that is to *shuffle* the list of responses. Then you can return sequential entries from the array. The randomness happens in the shuffle but that won't repeat entries (until you run out of entries, of course). – Pointy Feb 16 '23 at 21:36
  • 1
    What you want to look for is the Fisher-Yates shuffle algorithm, which is very simple. – Pointy Feb 16 '23 at 21:39

0 Answers0