[SOLVED] Count matching letters once

Issue

I’m creating a kid’s learning tool that has a form which matches 4 letters to a word.

I want to count the number of character matches in a word. But it counts duplicates of letters as 2 instead of 1. For example if the word is "loot", and the user submits "flop", the matching letters are 3 instead of 2, because it’s counting "o" twice. How do I fix this? Many thanks

       function countMatching(str1, str2) {
            var c = 0;

            for (var i = 0; i < str1.length; i++) {

              if (str2.includes(str1[i]))
                c += 1;
                
            }
            matchingLetters = c;
          }

Solution

I made an alternative version of @cmgchess’ answer, which creates an array of the actual solution of letters to still guess, and removes each letter as it is encountered in the entered solution.

let matchingLetters;

function countMatching(str1, str2) {
            var c = 0;
            str1Arr = str1.split('');
            
            for (var i = 0; i < str2.length; i++) {

              if (str1Arr.includes(str2[i])) {
                c += 1;
                str1Arr.splice(str1Arr.indexOf(str2[i]), 1);
              }
                
            }
            matchingLetters = c;
          }
          
          
countMatching('loot', 'boot') 
console.log(matchingLetters)

Answered By – fravolt

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.