samedi 24 août 2019

How can I get a new random item from an array excluding the ones that were already picked? [duplicate]

I've seen other posts about the issue but the difference here is that I will need the new value stored in a different variable and use it as an index for another array to change some buttons text content.

 //The 'value' in this case is an array that contains 4 strings.

 const randomNumber0 =  Math.floor(Math.random()*value.length)
 const randomNumber1 =  Math.floor(Math.random()*value.length)
 const randomNumber2 =  Math.floor(Math.random()*value.length)
 const randomNumber3 =  Math.floor(Math.random()*value.length)


 //Here the value is used to change all of the button's text content based 
 on the randomly generated numbers from the above snippet 

 document.querySelector('#btn1').textContent = value[randomNumber0]
 document.querySelector('#btn2').textContent = value[randomNumber1]
 document.querySelector('#btn3').textContent = value[randomNumber2]
 document.querySelector('#btn4').textContent = value[randomNumber3]



 The problem here is that the buttons will get repetitive text content 
 as the numbers above will repeat most of the times.

 I would like to be able to pass the 'btn2''s index value another value 
 that gets randomized from the other numbers that were not already 
 selected for the 'btn1'. 

 For example. I will let document.querySelector('#btn1').textContent = 
 value[randomNumber0] unchanged and let's say randomNumber0 generates the 
 number 1. 

 For the 'btn2' I would like to have value[randomNumber1] where 
 randomNumber1 to generate a number that excludes the number 1, which was 
 picked by randomNumber0. So, the result should be a new random number 
 from this array[0, 2, 3].

 I would like as well to be able to repeat the process for 'btn3', and 
 'btn4'. 

 Many thanks in advance for clarifying this issue.




Aucun commentaire:

Enregistrer un commentaire