Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop doesn't iterate in function

This code returns false and I think it should return true


function containss(arr, charr)
{
 for (let w = 0; w < arr.length; w++)
 {
   //console.log(arr[0][q]);
   console.log(arr[0][w]);
   if (arr[0][w].toLowerCase() === charr[0].toLowerCase())
   {
     return true;
   }
 }
 return false;
}

  
let arr2 = ["Hello"];
console.log(containss(arr2, "e"))


I’ve tried playing with indexes and it works(returns true) ONLY if i change the letter passed to H or h. Please help I am going mad

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because you pass an array with one string element you need to iterate over the first array item, e.g. test for arr[0].length instead of arr.length:

function contains1(arr, char) {
 for (let w = 0; w < arr[0].length; w++) {
   console.log(arr[0][w]);
   if (arr[0][w].toLowerCase() === char.toLowerCase()) {
     return true;
   }
 }
 return false;
}

function contains2(arr, char) {
 return arr[0].indexOf(char) >= 0;
}

  
let arr2 = ["Hello"];
console.log(contains1(arr2, "e"))
console.log(contains2(arr2, "e"))

Note the shortened version contains2()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading