PomyloneKodowanie
PomyloneKodowanie

Reputation: 3

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

Upvotes: 0

Views: 48

Answers (2)

JEEngineer
JEEngineer

Reputation: 166

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"));

Upvotes: 0

Peter Thoeny
Peter Thoeny

Reputation: 7616

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

Upvotes: 1

Related Questions