Given the array ["cat", "dog", "reindeer", "penguin", "crocodile"], print all words with at least 4 consonants.
I don't know how to do it.
CodePudding user response:
The commented code below can help you:
const animals = ["cat", "dog", "reindeer", "penguin", "crocodile"]
const vowels = ['a', 'e', 'i', 'o', 'u']
animals.forEach(animal=>{
let counter=0
//spliting the word in letters
animal.split('').forEach(letter=>{
//checking if the letter is really a letter and if it is not a vowel
if(letter.toLocaleLowerCase()>='a'&&letter.toLocaleLowerCase()<='z'&&!vowels.some(v=>v===letter.toLocaleLowerCase()))
counter
})
if(counter>=4)
console.log(animal)
})
CodePudding user response:
With String match()
method for pattern-matching, and Array.prototype.filter()
for conditional screening of items, we can write a concise one-liner:
> const animals = ["cat", "dog", "reindeer", "penguin", "crocodile"]
> animals.filter( animal => animal.match(/[^aeiou]/gi).length >= 4)
["reindeer", "penguin", "crocodile"]
Do study regex
as much as possible. Here are few resources: quick overview, deatiled demo