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

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

Leave a Reply