0

I'm trying to alternate between players and give each one a question, now the players names are stored in an array, I'm trying random, but it's not working.

var counter = 0;
const limit = 4 * localStorage.getItem('playersNum');

nextBtn.addEventListener('click', function() {
  if(counter < limit) {
    // Display player's name and ask question
    for (let i = 0; i < names.length; i++) {
        randomName = names[Math.floor(Math.random()*names.length)];
        const playerName = document.getElementById('card-title');
        playerName.innerText = randomName;

    }
    const h6 = document.getElementById('h6');
    h6.innerHTML = "Question " + (counter + 1);
    nextBtn.innerHTML = "Next";
    // Randomely pick a question from the array
    randomItem = questions[Math.floor(Math.random()*questions.length)];
    random = document.getElementById('questions');
    random.innerText = randomItem;
    counter++; 
  } else {
    alert('No more questions !')
  }
});

1 Answers1

0

You can use shuffle: [https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array]

var counter = 0;
const limit = 4 * localStorage.getItem('playersNum');

questions = shuffle(questions);
names = shuffle(names);
nextBtn.addEventListener('click', function() {
    if(counter < limit) {
        // Display player's name and ask question
        randomName = names[counter%names.length];
        const playerName = document.getElementById('card-title');
        playerName.innerText = randomName;
        const h6 = document.getElementById('h6');
        h6.innerHTML = "Question " + (counter + 1);
        nextBtn.innerHTML = "Next";
        // Randomely pick a question from the array
        randomItem = questions[counter)];
        random = document.getElementById('questions');
        random.innerText = randomItem;
        counter++; 
    } else {
        alert('No more questions !')
    }
});

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}