Randomly choose an item from a javascript array without repeating or destroying the array Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Randomly choose an item from a javascript array without repeating or destroying the array without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to serve words from an array to the user each time a button is clicked. I would like to serve the words randomly and not repeat. However, I don’t want to splice the served word from the array (ultimately the array items are going to be audio recordings for dictation and I want the user to be able to repeat the word if necessary).

I have tried a few things and most shortest solutions seem to involve splicing the array which ultimately destroys it. This, I don’t think, is correct for my case.

Here is the code (and here it is in JSFiddle):

var usedModuleOneWords = [];
var moduleOneArray = ["sit", "sat", "mat"];
var combined = (moduleOneArray, usedModuleOneWords);

const placeWordFromList = function() {
    for (const v of new Set([...moduleOneArray, ...usedModuleOneWords]))
        if (moduleOneArray.filter(e => e === v).length !== usedModuleOneWords.filter(e => e === v).length)
            {
            const randomWord = Math.floor(Math.random() * moduleOneArray.length);
            const displayWord = (randomWord, moduleOneArray[randomWord]);
            document.getElementById("word").innerHTML = displayWord;
            usedModuleOneWords.push(displayWord);
            console.log(usedModuleOneWords);
            } else {
            console.log("All Words Used!");
        }
}

Answer

Just think it simple

const placeWordFromList = function() {
    let randWord = moduleOneArray[Math.floor(Math.random() * moduleOneArray.length)];
    console.log(randWord);
    
    if(usedModuleOneWords.length >= moduleOneArray.length){
        console.log('All words are used!');
    } else if(usedModuleOneWords.indexOf(randWord) == -1){
      console.log(randWord);
      document.getElementById('word').innerHTML = randWord;
      usedModuleOneWords.push(randWord);
    } else{
      placeWordFromList();
    }
}

Here is the JSFiddle

We are here to answer your question about Randomly choose an item from a javascript array without repeating or destroying the array - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji