OiO.lk Blog HTML How to efficiently randomly select array item without repeats?
HTML

How to efficiently randomly select array item without repeats?


appreciate any answers on this as I have been really struggling to make it work in different ways.

So, I have an array. When I click a button, I want a random value from that array to appear. When I click it again, I want only values that have not already appeared to be displayed. I’m not sure if this is possible with math.random as I’ve tried multiple different ways of doing this, and now currently have an infinite while loop going (I had a for loop before).

Basically, no matter what methods I have tried, I keep getting the same values pop up again. I’ve also tried .pop(), but then the indexes for the values change and I don’t know how to keep track of that.

This is what I have right now:

HTML:

<h1 id="myValue"></h1>
<button onclick="showValue()">Click here!</button>

JavaScript:

myArray = [1, 2, 3];

function showValue() {
  while (myArray.length > 0) {
    let valueChoice = myArray[Math.floor(Math.random() * myArray.length)];
    const isValue1 = myArray.indexOf(1);
    const isValue2 = myArray.indexOf(2);
    const isValue3 = myArray.indexOf(3);
    if (valueChoice === isValue1) {
      myArray.splice(isValue1, 1);
      document.getElementById("myValue").innerHTML = "Value 1";
    } else if (valueChoice === isValue2) {
      myArray.splice(isValue2, 1);
      document.getElementById("myValue").innerHTML = "Value 2";
    } else if (valueChoice === isValue3) {
      myArray.splice(isValue3, 1);
      document.getElementById("myValue").innerHTML = "Value 3";
    }
    else {
      document.getElementById("myValue").innerHTML = "Error";
    }
  }
}



You need to sign in to view this answers

Exit mobile version