Home > Enterprise >  How do I make names that start with the letter K appear only in the console
How do I make names that start with the letter K appear only in the console

Time:03-21

i need to make names that start with the letter K appear only in the console

let friends = ["keven", "Khaled", "keiven", 1, 2, "coder", "zein"];
let i = 0;
let counter = 0;


while (i < friends.length) {
    console.log(friends[i])
    i  
    if (friends[i][counter] === friends[i].includes("A")) {
        continue;
    }
}

CodePudding user response:

  1. loop over the array
  2. get the first letter as lowerCase
  3. check if it equals to 'k'

    const friends = ["keven", "Khaled", "keiven", 1, 2, "coder", "zein"];
    for(let friend of friends){
        if(String(friend[0]).toLowerCase() === 'k'){
            console.log(friend);
        }
    }

CodePudding user response:

You can use the forEach syntax to cycle over your array, and then printing only the elements matching your request (so elements that are string and starts with a "k" letter).

friends.forEach((elem) => {
  if(elem.toString().toLowerCase().startsWith("k"))
    console.log(elem)
})
  • Related