-1

I'm trying to write a looping code that will remove all the names starting with the letter "a" but I'm not sure how to get it to work properly

let friends = ["Adam", "John", "Bernard", "Jacoub", "Arnold", "Kaytlen", "Samir"];
let letter = "a";

for (let i = 0; i < friends.length; i++){
if(friends[i][0] === "A"){
    continue;
}
    console.log(`${i} => ${friends[i]}`);

}

The problem is I want to write each index number before the name, but when I use continue; it removes the whole thing and I get this output

//"1 => John"

//"2 => Bernard"

//"3 => Jacoub"

//"5 => Kaytlen"

//"6 => Samir"

Notice how index 0, 4 are missing

3 Answers3

0

When the if statement evaluates to true, the continue statement is reached. This statement tells JavaScript to move on to the next iteration of the loop, therefore, the names starting with "A" is not logged to the console.

LeKoels27
  • 13
  • 5
  • I'm not sure what you are trying to achieve, but if you want an array containing a list of friends that's name Do Not start with the letter "A", I would suggest using the `filter` array method as @kelly mentioned. – LeKoels27 Aug 20 '22 at 14:13
0
let friends = ["Adam", "John", "Bernard", "Jacoub", "Arnold", "Kaytlen", "Samir"];
let letter = "a";

friends =  friends.filter(function(friend){
  return !friend.toLocaleLowerCase().startsWith(letter)
})
for (let i = 0; i < friends.length; i++){

    console.log(`${i} => ${friends[i]}`);

}
Anwar Ul-haq
  • 1,851
  • 1
  • 16
  • 28
0

In keeping with your original code here is one approach:

let friends = ["Adam", "John", "Bernard", "Jacoub", "Arnold", "Kaytlen", "Samir"];
let letter = "a";
    
 for(let i = 0; i < friends.length; i++) {
     if(friends[i][0].toLowerCase() === letter.toLowerCase()) {
         friends.splice(i, 1);
         i--;
     }
     console.log(`${i} => ${friends[i]}`);
 }

The reason for the i-- is if there is an adjacent element that also matches the criteria

Robert
  • 10,126
  • 19
  • 78
  • 130