Luis Ulua Luis Ulua - 2 months ago 5
Javascript Question

Comparing 2 strings in array to match J.S

"Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array."
For some reason I can pass every other checkpoint except (["hello", "hey"]). any tips?

function mutation(arr) {
var firstIndex = arr[0].toLowerCase();
var secondIndex = arr[1].toLowerCase();

for(var i = 0; i < arr.length; i++) {
if(firstIndex.indexOf(secondIndex.charAt(i)) !== -1) {
return true;
}
else {
return false;
}
}
return arr;
}

mutation(["hello", "hey"]);

Answer

The idea is to check every character in secondIndex to see if it is contained in firstIndex. So the logic here would be: for ever character in secondIndex, if the character is not in firstIndex, return false (ending the function). If the function doesn't end after checking all the characters, you know that each character was found in firstIndex, and you can then return true.

function mutation(arr) { 
  var firstIndex = arr[0].toLowerCase(); 
  var secondIndex = arr[1].toLowerCase();

  for(var i = 0; i < secondIndex.length; i++) {
    if(firstIndex.indexOf(secondIndex[i]) === -1) { 
      return false;
    }
  }
  return true;
}

mutation(["hello", "hey"])
Comments