Home > database >  How to add a condition to this loop in javascript
How to add a condition to this loop in javascript

Time:08-21

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

CodePudding user response:

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.

CodePudding user response:

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

let letter = "a";

function filteredNames(names, letter){
  return names?.filter((name) => name.charAt(0) !== letter.toUpperCase())
}

filteredNames(friends, letter)?.forEach((name, index) => {
  console.log(name, index)
})

CodePudding user response:

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]}`);

}

CodePudding user response:

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

  • Related