Home > Mobile >  Loop doesn't iterate in function
Loop doesn't iterate in function

Time:01-03

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

CodePudding user response:

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

CodePudding user response:

To get this working with more than one word in the array, you could use array.some().

function contains(arr, compareCharacter) {
  return arr.some((item) => {
    return item.split("").some((character) => {
      return character.toLowerCase() === compareCharacter.toLowerCase();
    });
  });
}

let arr2 = ["Hello", "test"];
console.log(contains(arr2, "t"));

  • Related