Home > Back-end >  How to take three different words from an array?
How to take three different words from an array?

Time:11-04

I want to create a function taking three random different words from an array

I followed React native filter array not working on string to filter the array. However, the filter is not working.

takeThreeWords=()=>{
    for(i=0;i<3;i  ){
    rand =(max, min=0)=> Math.floor(Math.random()*max-min)
    randomWord=()=> this.state.wordsBank[rand(this.state.wordsBank.length)]
    let aRandomWord = randomWord()
    
    this.setState(prevState=>({
      wordsToUse:[...prevState.wordsToUse, aRandomWord],
      wordsBank: prevState.wordsBank.filter(word=>word!== aRandomWord)

    }))

The last line is to make sure that no words from wordsBank are taken twice. However, the function works just as if the last line does not exist. wordsToUse take three words, but sometimes they are the same...

Can you please point me out what I am missing ?

CodePudding user response:

You are updating wordsBank via this.setState, but your loop keeps operating on the initial copy of wordsBank, which has not been filtered.

The cleanest fix is to not call this.setState multiple times in a loop.

let wordsBank = this.state.wordsBank;
let extractedWords = [];
while(extractedWords.length<3) {
  let i = ~~(Math.random()*wordsBank.length);
  extractedWords.push(wordsBank.splice(i, 1)[0]);
}

this.setState(prevState=>({
  wordsToUse: [...prevState.wordsToUse, ...extractedWords],
  wordsBank
}));
  • Related