Home > Net >  Replace duplicate value in a an array in JavaScript
Replace duplicate value in a an array in JavaScript

Time:12-15

let lettersOfTheWord =["W",'H','A','T','E','V','E','R'];
let guessedLetters = lettersOfTheWord.map(()=>'_');
var count=0;
function guessLetter(letter){
    for(let i=0; i<lettersOfTheWord.length;i  ){
        if (letter===lettersOfTheWord[i] && guessedLetters[i]==='_'){
            guessedLetters[i]=letter;
            console.log("You entered:"   letter);
            console.log(`The current guessed letters: ${guessedLetters.toString()}`);
            console.log("Congradulations! You found a new letter.");
            count  ;
            console.log(count);
        }
        if (letter!==lettersOfTheWord[i] && guessedLetters[i]!=='_'){
            console.log("wrong letter");
        }
    }
    if (count===lettersOfTheWord.length){
        console.log("you win");
    }
}
   

guessLetter("W");
guessLetter("H");
guessLetter("A");
guessLetter("T");
guessLetter("E");
guessLetter("H");
guessLetter("E");
guessLetter("R");

So I have changed my code now. The new problem is what if I would like to print out the "wrong letter" information if the call function has a wrong argument?


 let lettersOfTheWord =['F','O','X',"X"];
 let guessedLetters = [];
 let generateUnderScore = function(word){
    for (let i =0; i<word.length; i  ){
        guessedLetters.push("_");
    }
    //console.log(guessedLetters.toString());
    return guessedLetters;
} //to generate underscore.
generateUnderScore(lettersOfTheWord);
 let guessLetter =function(letter){
     for (let i=0; i<lettersOfTheWord.length;i  ){
         if (letter===lettersOfTheWord[i]){
             let index=lettersOfTheWord.indexOf(letter);
             guessedLetters[index]=letter;
             console.log(guessedLetters);
    
         }
     }
     console.log("You entered:"   letter);
     console.log(`The current guessed letters: ${guessedLetters.toString()}`);
     console.log("Congradulations! You found a new letter.")

     
    }
 

  guessLetter("F");
  guessLetter("O");
  guessLetter("X");
  guessLetter("X");

This is what my code looks like, for the last function call guessLetter("X"), I would like the output to be something like:

You entered:X
The current guessed letters: F,O,X,X
Congratulations! You found a new letter.

However, it ends up with:

You entered:X
The current guessed letters: F,O,X,_
Congratulations! You found a new letter.

I noticed the duplicate of letter "X" was not replaced, but how do I fix this problem? Thank you so much!

CodePudding user response:

Your Issue:

When you try to find the index of "X" from lettersOfTheWord, it will always return 2 which is the fist occrance of "X" in lettersOfTheWord

Fix to your problem.

Array.prototype.indexOf() accepts fromIndex as an optional parameter. You can use the index of the execution as the fromIndex.

Your Fixed Fiddle

let lettersOfTheWord = ['F', 'O', 'X', "X"];
let guessedLetters = [];
let executionIndex = 0;
let generateUnderScore = function (word) {
  for (let i = 0; i < word.length; i  ) {
    guessedLetters.push("_");
  }
  //console.log(guessedLetters.toString());
  return guessedLetters;
} //to generate underscore.
generateUnderScore(lettersOfTheWord);
let guessLetter = function (letter) {
  for (let i = 0; i < lettersOfTheWord.length; i  ) {
    if (letter === lettersOfTheWord[i]) {
      let index = lettersOfTheWord.indexOf(letter, executionIndex);
      guessedLetters[index] = letter;
      // console.log(guessedLetters);
    }
  }
  console.log("You entered:"   letter);
  console.log(`The current guessed letters: ${guessedLetters.toString()}`);
  console.log("Congradulations! You found a new letter.");
  executionIndex  ;
}
guessLetter("F");
guessLetter("O");
guessLetter("X");
guessLetter("X");

Better Solution

You can rewrite guessedLetters using Array.map. For loop isirrelavent, you can use Array.indexOf itself and can check whether the found index is greater that -1, which means element exist in array.

Working Fiddle

let lettersOfTheWord = ['F', 'O', 'X', "X"];
let guessedLetters = lettersOfTheWord.map(item => '_');
let executionIndex = 0;

let guessLetter = function (letter) {
  const index = lettersOfTheWord.indexOf(letter, executionIndex);
  index > -1 ? guessedLetters[index] = letter : {};
  console.log("You entered:"   letter);
  console.log(`The current guessed letters: ${guessedLetters.toString()}`);
  console.log("Congradulations! You found a new letter.");
  executionIndex  ;
}
guessLetter("F");
guessLetter("O");
guessLetter("X");
guessLetter("X");

CodePudding user response:

I little bit of simplified your code.

let lettersOfTheWord =['F','O','X',"X"];
let guessedLetters = lettersOfTheWord.map(()=>'_');

function guessLetter(letter){
    lettersOfTheWord.forEach((_letter,i)=>{
        if (letter===_letter && guessedLetters[i]==='_'){
            guessedLetters[i]=letter;
            console.log(guessedLetters);
            console.log("You entered:"   letter);
            console.log(`The current guessed letters: ${guessedLetters.toString()}`);
            console.log("Congradulations! You found a new letter.")
        }
    });
}

guessLetter("F");
guessLetter("O");
guessLetter("X");
guessLetter("X");

The problem was in your if you should add && guessedLetters[i]==='_' to your code. And remove let index=lettersOfTheWord.indexOf(letter); then replace i instead of index

Also, you can use the for ... in loop. To use the break and skip unnecessary checks

let lettersOfTheWord =['F','O','X',"X"];
let guessedLetters = lettersOfTheWord.map(()=>'_');

function guessLetter(letter){
    for(const i in lettersOfTheWord){
        if (letter===lettersOfTheWord[i] && guessedLetters[i]==='_'){
            guessedLetters[i]=letter;
            console.log(guessedLetters);
            console.log("You entered:"   letter);
            console.log(`The current guessed letters: ${guessedLetters.toString()}`);
            console.log("Congradulations! You found a new letter.");
            break;
        }
    }
}

guessLetter("F");
guessLetter("O");
guessLetter("X");
guessLetter("X");

TIPS:

  • you can remove function generateUnderScore
  • learn more about ES6 map & forEach
  • you don't need to provide function to your let. Just create function name(..) {...} I think, this is more clerable
  • Related