JSFiddle - React, Tailwind, and code Playground

by zxzc0

JavaScript

let words = [{
    q: 'A',
    a: 'a'
  },
  {
    q: 'B',
    a: 'b'
  },
  {
    q: 'C',
    a: 'c'
  },
  {
    q: 'D',
    a: 'd'
  },
  {
    q: 'E',
    a: 'e'
  },
  {
    q: 'F',
    a: 'f'
  },
];

const button = document.getElementById("button");
const word = document.getElementById("word");

const rng = () => {
  if (words.length > 0) {
    const rando = Math.floor(Math.random() * words.length); //get a random num in range
    const selectedWord = words[rando]; //get word object from array
    word.innerText = selectedWord.q; // update text with q of selected word object
    words.splice(rando, 1); // remove word object from the array so it's not possible to get it next time you press the button
  } else {
    alert('all out of words');
  }
}

button.addEventListener('click', () => {
  rng();
});