Tell us what’s happening:
So I feel stuck. I’ll put comments down below with my code to clarify what I’m attempting.
It seems as though my code is broken here:
if (firstArr.indexOf(secondArr[i]) > 0)
because the console logs true and then false. It’s as if it is skipping over the first character/first string in the array.
I can’t figure out why.
Your code so far
function mutation(arr) {
let comparison = 0; //I'm incrementing this variable by 1 for each character from the second string that is contained in the first string. I then compare the number with the length of the second string.
let firstStr = arr[0].toLowerCase();
let secondStr = arr[1].toLowerCase();
let firstArr = firstStr.split("");
let secondArr = secondStr.split("");
for (let i = 0; i <= secondArr.length; i++) {
if (firstArr.indexOf(secondArr[i]) > 0) {
comparison++;
console.log(comparison)
return (comparison === secondArr.length);
}
}
return false;
}
mutation(["hello", "hey"]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.
I’m not sure why that one is coming back as undefined
function mutation(arr) {
let comparison = 0;
let firstStr = arr[0].toLowerCase();
let secondStr = arr[1].toLowerCase();
let firstArr = firstStr.split("");
let secondArr = secondStr.split("");
for (let i = 0; i < secondArr.length; i++) {
let current = firstArr.indexOf(secondArr[i]);
console.log(secondArr.length) //logs 3 as expected
console.log(current) // logs 0 as expected
console.log(current > -1) // logs true as expected
if ( current > -1) {
comparison++;
return (comparison == secondArr.length);
}
}
return false;
}
mutation(["hello", "hey"]);
Okay I see my problem with the syntax. It should have had parentheses.
I also see that the return should occur after the for loop has run it’s course. Correct me if I’m wrong, but the problem was that I was returning the comparison before the loop had completed?