0

I've got an array, rWords that could be any length. I'm trying to develop a function that chooses six at random and assigns them as text in six divs, that will be options for users to click in a quiz type game.

My problem: I can get a random array of six words from rWords and assign them as text. However it sometimes happens that you get the same word twice in the array, which i dont want.

The random word funtion: (there are six squares on the html)

Function randomWord(){

  var pArr = [];

  for (i=0; i<squares.length; i++){
    var p = Math.floor(Math.random() * rWords.length);
    pArr.push(rWords[p]);
  }
  return pArr;
}

I'm trying to return as an Array so I can use Array.from(set) to create a unique array for the 'answers' I havnt completed the squares function fully as everything I've tried doesnt work. When I was returning random words one at a time it was I cannot get the array to pass as a single Array. I can get six arrays to pass, with one element in each.

To fill the squares:

For(i=0; i<squares.length;i++){
  Squares[i].textcontent = randomWord();
}
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Tom Lee
  • 11
  • 3
  • You'll want to *shuffle* the array (randomly) and then consume the values from *that* array one by one. There are several questions on how to shuffle an array. – trincot Oct 18 '19 at 14:22
  • trincot's comment points to one of the many ways to do this, I've added another duplicate that talks about some others as well. Related searches to do: [\[js\] pick random non-repeating](/search?q=%5Bjs%5D+pick+random+non-repeating), [\[js\] pick random unique](/search?q=%5Bjs%5D+pick+random+unique). More on searching [here](/help/searching). – T.J. Crowder Oct 18 '19 at 14:25

1 Answers1

0

I think this is what you're looking for?

rWords = [
  "foo",
  "bar",
  "baz",
  "boo",
  "help",
  "me",
  "everything",
  "is",
  "alright"
]

function shuffle(array) {
  array.sort(() => Math.random() - 0.5);
}

function randomWord() {
  var pArr = [];
  words = rWords.slice()
  for (i=0; i<6; i++){
    shuffle(words);
    pArr.push(words.pop())
  }
  return pArr;
}

console.log(randomWord())
console.log(randomWord())
console.log(randomWord())

Output:

[ 'alright', 'everything', 'is', 'boo', 'help', 'bar' ]
[ 'alright', 'help', 'is', 'me', 'foo', 'boo' ]
[ 'me', 'alright', 'everything', 'bar', 'help', 'baz' ]
Nick Martin
  • 731
  • 3
  • 17