0

On a button click, I want to run a function that will each time randomly select an option from a select dropdown that wasn't chosen before. And if all options were chosen, I want to reset the used options and start from the beginning.

I have a function that chooses an element that wasn't chosen before randomly from an array (credit to @Rajesh)

function randomize(arr) {
  let data = [...arr];
  let chosenItems = [];

  function getRandomValue() {
    if (data.length === 0) {
      data = chosenItems;
      chosenItems = [];
    }
    const index = Math.floor(Math.random() * data.length);
    const choice = data.splice(index, 1)[0];

    chosenItems.push(choice);
    return choice;
  }
  
  return {
    randomItem: getRandomValue
  }
}

const dummyData = [ 1,2,3,4,5 ];

const randomizeData = randomize(dummyData);

for (let i = 0; i< 10; i++) {
  console.log(randomizeData.randomItem())
}

I have already created a script that randomly chooses an element from a select2 dropdown but it selects the same element very often.

var optionsArray = new Array();
var first = $('select option')[0];
$('select option').each(function () { optionsArray.push(this) });

if (optionsArray.length > 1) {
    $('select').html('');

    var i = 0;

    var random

    while (i < optionsArray.length) {

        random = Math.floor(Math.random() * optionsArray.length)
        //if element hasn't been marked as "selected"
        if (optionsArray[random] != "selected") {
            $("select").append(optionsArray[random]);
            //mark element as selected
            optionsArray[random] = "selected"
            i++
        }
     }

    var newSelectedOption = $('select option')[0];
    $('select').val($(newSelectedOption).val()).trigger('change');
Anatol
  • 3,720
  • 2
  • 20
  • 40
  • @GetSet I actually had a working script that selected a random option in a dropdown. I was simply using `Math.random()` but I soon found out that it would choose the same option pretty often. So I wanted to create a function that would select an option that wasn't chosen before. I tried to create a new function but it became really long and in my opinion, not very efficient and robust... So that's why I wanted to check if anyone had better ideas than mine. – Anatol Mar 23 '20 at 11:42
  • Ok i see. Can you post your code anyway? Would serve as a good starting point on good faith. Specifically your code as it relates to the html and javascript pertaining to the "dropdown". ... Someone downvoted you. But I will upvote you back. This may bring your question more attention. – GetSet Mar 23 '20 at 11:46
  • @GetSet I edited my post and added my previous function that selected an option randomly. – Anatol Mar 23 '20 at 11:50

1 Answers1

1

<html>
     <body>
          <select id="dropdown">
               <option value="1">1</option>
               <option value="2">2</option>
               <option value="3">3</option>
          </select>
          <button id="btn">
               Generate
          </button>
     </body>
     <script>
          let dropdown = document.getElementById('dropdown');
          var options = [];
          var chosenItems = [];
          function setOptions(){
               for(var i = 0; i < dropdown.options.length; i++)
                    options.push(dropdown.options[i].value);
          }
          document.getElementById('btn').addEventListener("click", function(){
               options = options.filter( function( el ) {
                    return chosenItems.indexOf( el ) < 0;
               });
               if(options.length == 0){
                    console.log("reset data")
                    setOptions();
                    chosenItems = [];
               }
               var unSelectedRandom = options[Math.floor(Math.random() * options.length)]
               for(var i = 0; i < dropdown.options.length; i++){
                    var current = dropdown.options[i]
                    if ( current.value == unSelectedRandom ) {
                         dropdown.selectedIndex = i;
                         chosenItems.push(current.value);
                         console.log("chosen: "+chosenItems)
                    }
               }
          });
     </script>
</html>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48