freeCodeCamp Challenge Guide: Mutations

can someone tell me what’s wrong with my code?? I don’t know why it’s not working for the first mutation but is working for the rest.

 function mutation(arr) {
      var array = arr.join(',').toLowerCase().split(",");
  
  var compare = array[1].split("");

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

  }
  
}

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

Hi campers . this is my code. Its not working with all tests, I could use some help to spot that bug.

function mutation(arr) {

for(j=0;j<arr.length;j++){
arr[j].toLowerCase();
b = [];
b = arr[1].split(’’);
for(i=0;i<b.length;i++){

result = arr[0].indexOf(b[i]);
if (result !== 0){
  return true;
}else{
  return false;
}

}
}
return arr;
}

I split arr[1] into letters, creating oneArr, then I used a while loop to add 1 to n as long as the letters from oneArr were present in arr[0]. So if the loop stops executing when n < oneArr.length ,it means one of the letters isn’t present and the function will return ‘false’.

function mutation(arr) {

var oneArr = arr[1].toLowerCase().split("");
var n=0;
while ((arr[0].toLowerCase().indexOf(oneArr[n]) > -1) && (n < oneArr.length)) {
n++;
}
if ((n < oneArr.length) === true) {
return false;
}
return true;
}

1 Like

Babu, creating that empty b variable isn’t necessary if you declare it in the next line. Still, you need to use var before introducing a new variable so that should go before b = arr[1].split(’’). I can’t imagine you’d have to use a double for loop for this task. Also, your final condition result !== 0 isn’t the right condition here. Read again about indexOf() and what the values it returns mean. Read the tips in the head of this thread, they helped me a lot.

[quote=“samnguyen94, post:69, topic:16025”]
var array = arr.join(’,’).toLowerCase().split(",");
[/quote] - I believe this line is unnecessary. You could just split arr into two simply indexing arr[0] and arr[1] and then change them toLowerCase. You use the name ‘array’ instead of ‘arr’ all throughout your code. ‘array’ is never declared here

Thanks , I did some reading, used var to declare an empty array, didn’t see the need to split but definitely lower cased my strings. This is what I came up with.

function mutation(arr) {
var newArray = [];
for (i=0;i<arr.length;i++){

newArray.push(arr[i].toLowerCase());

}for(j=0;j<newArray[1].length;j++){
if (newArray[0].indexOf(newArray[1][j]) === -1){
return false;
}

}
return true;}.

1 Like
function mutation(arr) {
  let string1 = arr[0].toLowerCase();
  let string2 = arr[1].toLowerCase();
    
  let letterInStr = true;
  let i = 0;
  
  while (i < string2.length && letterInStr === true) {
    letterInStr = string1.includes(string2[i])
    i = i + 1;
  }

  return letterInStr;
}

let result = mutation(["Mary", "Aarmy"]);
console.log(result);
2 Likes