0

I have an array which consists of 6 values. I am running Math.random to shuffle it. However, it's shuffling the array every time and displaying a value which is repeating. I want to shuffle the array and get 1 unique value. This value should be removed from the array until every other value if fetched. For example, if an array has items 1,2,3,4 and after shuffling it the answer is 3. Now, I want it to exclude the 3 and fetch a new value from 1,2,4.

I


    const params = {
      icon_emoji: ':laughing:'
    };
    var members=['1','2','3','4','5','6','7'];
    var assignee = members[Math.floor(Math.random()*members.length)];

      bot.postMessageToChannel('general', `It's ${assignee}'s turn today!`, params);


}

function results() {


    const params = {
      icon_emoji: ':laughing:'
    };
    bot.postMessageToChannel('general', `Inside results`, params);


}

user11066242
  • 153
  • 4
  • 15

2 Answers2

2

Your definition of "shuffle" is incorrect... Rather than picking random items from an array then having to splice them out of the array, why not actually shuffle (i.e. reorder in random order) the entire array using a Fisher-Yates shuffle then just pop elements out of that array?

The shuffle function below is reproduced from this answer:

function shuffle(array) {
  let 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;
}

const myArr = [1, 2, 3, 4, 5, 6];
shuffle(myArr);
while (myArr.length > 0) {
  console.log(myArr.pop());
}

Think twice before attempting to write your own shuffling algorithm... Cleverer people than you or I have badly messed up on this before.

spender
  • 106,080
  • 28
  • 202
  • 324
1

You can use array.splice function to remove an item from the array

members.splice(Math.floor(Math.random()*members.length), 1);

Note: If you want to retain your original array, I would recommend you to create a temp array and do the manipulations on that variable

Tushar
  • 11,306
  • 1
  • 21
  • 41