0

I'm getting 'false' for the first test and 'true' for the second test. I'm suppose to create a function that will evaluate to these values. I thought I executed my code in the function correctly but I'm not getting what I'm suppose to be getting. I don't understand what I could be doing wrong here. Any help will be so appreciated. Thanks.

// - Given the arrayOfNames, determine if the array contains the given name.
// - If the array contains the name, return true.  If it does not, return false.
// - Hint: Use a loop to "iterate" through the array, checking if each name matches the name parameter.
// 
// Write your code here 

function contains(arrayOfNames, name) {
  for (index = 0; index < arrayOfNames.length; index++) {
    if (arrayOfNames[index] === name) {
      return true;
    } else {
      return false;
    }
  }

}

//  -------TESTS---------------------------------------------------------------
//  Run these commands to make sure you did it right. They should all be true.
console.log("-----Tests for Exercise Five-----");
console.log("* Returns true when the array contains the name.");
console.log(contains(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"], "nancy") === true);
console.log("* Returns false when the name is not in the array");
console.log(contains(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"], "fred") === false);

1 Answers1

0

Return false only if the array doesn't contain the name.

What you're trying to do is it will return true if the match found but it will return false as soon as the match not found arrayOfNames[index] === name).

In you first example: Let say i=0 and the first element is bob. So the arrayOfNames[index] is bob and the name you want to search is nancy. So when it matches them it is not equal so it will return false.

function contains(arrayOfNames, name) {
  for (let index = 0; index < arrayOfNames.length; index++) {
    if (arrayOfNames[index] === name) {
      return true;
    }
  }
  return false;
}

//  -------TESTS---------------------------------------------------------------
//  Run these commands to make sure you did it right. They should all be true.
console.log("-----Tests for Exercise Five-----");
console.log("* Returns true when the array contains the name.");
console.log(
  contains(
    ["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"],
    "nancy"
  ) === true
);
console.log("* Returns false when the name is not in the array");
console.log(
  contains(
    ["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"],
    "fred"
  ) === false
);
DecPK
  • 24,537
  • 6
  • 26
  • 42