13aal 13aal - 7 months ago 12
Javascript Question

Checking if one element of an array's index is equal to the second element

I have this little script that will check if one element of an array (

arr[0]
) is equal to the second element of the array (
arr[1]
). However when it checks the following array I would expect it to return
false
, yet it returns
true
. so my questions are, why does this return
true
, and how can I fix it to return
false
like expected?

function mutation(arr) {
var elem0 = arr[0].toLowerCase();
var elem1 = arr[1].toLowerCase();

for(var x=0; x < elem1.length; x++){
check = elem0.indexOf(elem1[x]);
if(check === -1){
return false;
}
return true;
}
}

mutation(["hello", "hey"]); //returns true

Answer

you place the return true to soon

you need to place it after the for statement like so

 function mutation(arr) {
  var elem0 = arr[0].toLowerCase();
  var elem1 = arr[1].toLowerCase();

  for(var x=0; x < elem1.length; x++){
    check = elem0.indexOf(elem1[x]);
    if(check === -1){
      return false;
    }

  }
  return true;
}

mutation(["hello", "hey"]); //returns false