Search code examples
javascriptstringcompare

How do you check two strings in JS and determine if any letters in each is placed in the same letter row?


I have been searching high and low for a solution, but I cannot seem to find one. I am trying to make a function that checks two different strings to identify any words in the same position of each word, and output that as a number. An example:

"sterile" "meeting"

These two words have an E and an I in the same place. Never mind letters that exist in both, but scrambled (I have a solution for this, but it does not help me I'm afraid). I am trying to build something that outputs 2 for the two letters that do match.

So yeah, how would I get this to work? Code below is the non-working one, that checks for existing letters in both, and not if they match exactly within the words. Maybe I'm seeing something wrong with it?

var str1 = "sterile";
var str2 = "meeting";


function second() {
    return Array.prototype.filter.call(str1, function(c) {
        return str2.indexOf(c) === -1;
    }, this).join('');
}

function second() {
    return Array.prototype.filter.call(str1, function(c) {
        return str2.indexOf(c) === -1;
    }, this).join('');
}

console.log(second(str1, str2));
console.log(str1.length - second(str1, str2).length);
```

Solution

  • This should do the job

    const str1 = "sterile";
    const str2 = "meetinghey";
    
    
    const getSameLetters = (a, b) => {
      const minLength = Math.min(a.length, b.length);
      const sameLetters = []
      for (let i = 0; i < minLength; i++) {
        if (a[i] === b[i]) {
          sameLetters.push({ i, letter: a[i] })
        }
      }
      return sameLetters
    }
    
    console.log(getSameLetters(str1, str2))

    or the following, if you only care about the number of the same letters:

    const str1 = "sterile";
    const str2 = "meetinghey";
    
    
    const getSameLetters = (a, b) => {
      const minLength = Math.min(a.length, b.length);
      let sameLetters = 0
      for (let i = 0; i < minLength; i++) {
        if (a[i] === b[i]) {
          sameLetters++
        }
      }
      return sameLetters
    }
    
    console.log(getSameLetters(str1, str2))

    The idea behind those algorithms is this:

    1. Since we only want to find letters that match the same index in both words, we should iterate only until the end of the smallest word. Because you don't want to compare an undefined "char" to a "char" from another string - they will never match. So that's what Math.min(a.length, b.length) finds.
    2. Then we iterate from zero to minLength. On each loop cycle, we compare letters on the same index from a and b strings. If letters match, then we increment sameLetters by one, and continue the loop.
    3. Return sameLetters - that's the number we're looking for, the number of the same letter under the same index