Why does my code for the Mutations Algorithm pass all but one condition (the [“hello”, “hey”] should return false). https://www.freecodecamp.org/challenges/mutations
function mutation(arr) {
var arr1 = arr[0].toLowerCase();
var arr2 = arr[1].toLowerCase();
for(i=0; i < arr2.length; i++){
return arr1.indexOf(arr2[i]) !== -1;
}
}
mutation([“hello”, “hey”]);
Most significantly, you’r using the return
statement in your for
loop. This will immediately return from the function based on the first test. It only checks the first char. You need to find a way to return true if all chars are found and false on the first fail.
Thanks for your help, I got this to work:
function mutation(arr) {
var arr1 = arr[0].toLowerCase().split("");
var arr2 = arr[1].toLowerCase().split("");
for(i=0; i < arr2.length; i++){
if(arr1.indexOf(arr2[i]) === -1){
return false;
/*only return here if any index of arr2
does not match arr1. So for "hey" in the for loop:
"h" = true - don't return, "e" = true - don't return,
"y" = false - return.*/
}
}
return true;
/*the for loop will end if there are no instances where an
index of arr2 does not match arr1 (-1 means index doesn't exist);
outside the for loop the only option left is to return true*/
}
mutation(["hello", "hey"]);