How to Randomly Choose an Element from an Array that Wasn't Chosen before in JavaScript?

前端 未结 4 1016
遥遥无期
遥遥无期 2020-12-22 05:25

I want to run a function that each time randomly chooses an element from an array that wasn\'t chosen before. And if all elements were chosen, I want to reset the used eleme

4条回答
  •  北海茫月
    2020-12-22 05:57

    You can try something like this:

    Idea

    • Create a utility function that takes an array and returns you a random value.
    • Inside this Array, maintain 2 array, choices and data.
    • In every iteration, remove 1 item from data and put it in chosenItems
    • Once the length of data reaches 0, set chosenItems or originalArray as data and repeat process.

    Benefit of this approach would be,

    • You dont need to maintain and pass array variable.
    • It can be made generic and used multiple times.

    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())
    }

提交回复
热议问题