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);
```
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:
Math.min(a.length, b.length)
finds.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.sameLetters
- that's the number we're looking for, the number of the same letter under the same index