-1

Okay so I'm looping through all the elements on the page (3) that have the class 'possible'. Then I'm creating a variable called 'other' that randomly gets a value from the array otherAnswers. Then I'm taking those values and putting them into the respected elements as text. Only thing is, most of the time the loop selects the same variable from the otherAnswers array (sometimes once, sometimes twice, others three, and rarely none of the time). How do I make sure that once the .each loops through one of the values in the array, it doesn't get it again?

$('.possible').each(function(i, obj) {

    var other = otherAnswers[Math.floor(Math.random()*otherAnswers.length)];
    $(this).text(other); 
    //otherAnswers.splice(this);

});

I've tried the commented piece of code but that just removes the values so they don't show up on my page. I have a feeling that it has something to do with the variable 'i' in the function but i'm not sure.

Noah
  • 15
  • 3

1 Answers1

0

You can do this by taking the following steps:

Before looping, take a copy of the otherAnswers array, to avoid that you destroy it with what follows. For instance, with spread syntax:

var remainingAnswers = [...otherAnswers];

Then -- still before the loop -- shuffle the copied array randomly. Take the shuffle code from here.

shuffle(remainingAnswers);

Finally, inside your loop, access the values from that shuffled array, using the index i you already have:

var other = remainingAnswers[i];
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 2
    This works awesome, I don't even have to use the shuffle function because the otherAnswers array is already randomized. All I needed was ```var other = remainingAnswers[i];``` – Noah Aug 05 '19 at 16:23