13aal
13aal

Reputation: 1674

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

Upvotes: 0

Views: 113

Answers (4)

Redu
Redu

Reputation: 26161

The expression of this question has some logical flaws or at least some lacking points. Such as the given condition means that all the items in the array must be equal. If this is the case then just one tiny piece of instruction is sufficient

myArray.every(e => e == myArray[0])

var a = [1,1,1,1,1,1,1,1],
    b = ["hello", "hey"];

document.write("<pre> a array :" + a.every(e => e == a[0]) + "</pre>");
document.write("<pre> b array :" + b.every(e => e == b[0]) + "</pre>");

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68383

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])

It returns true since e is in both the elements hello and hey

Your code is essentially iterating over all the characters in the string.

You need to simply check

function mutation(arr) {
  return arr[0].toLowerCase() == arr[1].toLowerCase();
}

Upvotes: 1

Shomz
Shomz

Reputation: 37701

You're looping over a characters in a string (see what elem1 actually is), and therefore you get true because the first character of hey, which is h, is indeed found within the string hello.

If you want to wait for it to finish iterating over the whole string, use a boolean flag, and then return the value of that flag when the iterations are over.

However, seems you just want to compare the two elements:

return elem0 === elem1;

Upvotes: 1

Zamboney
Zamboney

Reputation: 2010

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

Upvotes: 1

Related Questions