0

Create an array and fill it with at least six usernames (i.e. “Sophia”, “Gabriel”, …) then loop through them with a for loop. If a username contains the letter “i” then alert the username.

I have tried to make an array and create and "if" statement, then I want to make an alert. I know I am missing something, but I can't figure out what.

  let userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];

  if(userNames.includes('i')){

    window.alert(userNames);
  }

I would like there to be a window alert with the name "mike"

3 Answers 3

1

That's not how includes works... for example:

const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];

console.log(userNames.includes('mike')) // true
console.log(userNames.includes('i')) // false

To get what you want you can do something like this:

 const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];
    
    userNames.forEach(name => {
      if(name.includes('i')) {
        console.log(name)
      }
    })

Sign up to request clarification or add additional context in comments.

Comments

1

Use a for loop if you want to return the index value of the array. In this case we treat the letter i as a regular expression by placing it between two forward slashes, and try to match that string in each array value. It then alerts you with the entire value (mike(

    let userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];
      for(let i = 0; i < userNames.length; i++) {
        if(userNames[i].match(/i/)) {
          window.alert(userNames[i]);
      }
    }

Comments

1

Iterate over the array with forEach then match it against a regular expression:

const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];
const regex = /i/;
userNames.forEach(name => {
  if (name.match(regex)) {
    alert(name);
  }
})

Or you could use includes:

const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];
userNames.forEach(name => {
  if (name.includes("i")) {
    alert(name);
  }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.