Check for element in array

Asked

Viewed 49 times

-4

I need to check if a name exists inside the array and return true if you find or false otherwise.

let names = ["Ana","João","Pedro","Maria"];

function hasName() {
  for (let i=0; i < names.length;i++) {
    if (names === "Pedro") {
      return true;
    }
  }
}
  • Welcome to [en.so]. Remember to always add a description to your post making it explicit what your difficulty is and what you’ve tried. Also note that you can use code formatting using the formatting bar while writing the post. This makes the post easier to read and understand and consequently will help you to have an answer.

  • After you finish doing this one read exercise on that link: Determining whether an array contains a certain element

  • 1

    Enjoy and see also about other methods like find, some, Every.

1 answer

1

You’re comparing the whole set using names == "Pedro". You should only use one element names[i].

See below working:

let names = ["Ana","João","Pedro","Maria"]
console.log(hasName())

function hasName() {
  for (let i = 0; i < names.length; i++) {
    if (names[i] == "Pedro") {
      return true;
    }
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.