Reputation: 83
This is a javascript function i included in my html, am able to counts each vowels and display each vowels total plus the highest vowel but i felt the code is too lengthy pls help to optimize, the use of the conditional statement is too much
Upvotes: 1
Views: 300
Reputation: 1
function vowelCount(str){
str=str.toLowerCase()
let count=[]
for(let i=0;i<str.length;i++){
if(str.charAt(i)=='u'||str.charAt(i)=='o'||str.charAt(i)=='i'||str.charAt(i)=='e'||str.charAt(i)=='a'){
count.push(str.charAt(i))//to store all the vowels in an array
}
}
let eachcount={}
count.forEach((x)=>eachcount[x]?eachcount[x]++:eachcount[x]=1) //to count each vowel from the count array
return eachcount
}
console.log(vowelCount("hello how Are You"))
Upvotes: 0
Reputation: 599
I see two simple ways to refactor your code:
First, the regular expression you use [aeiou] already makes sure that match[x] is one of these vowels. instead of writing an if statement to compare match[x]
against every single possible values, you could use an object initialised as such :
vowelCount = { a: 0, e: 0, i: 0, o: 0, u: 0 }
you can then increment the count of each vowel thus:
vowelCount[match[x]]++
Second, you write the same code again and again to determine what gets written on your page.
you could write a function that gets called with the vowel and the count for that vowel as parameter, and that would write to the correct element on your page. It could look like this.
function(vowel, count) {
document.getElementById(`L${vowel}`).innerHTML = `<input value=${count}>`
}
You could call that function by iterating over the array Object.keys(vowelCount)
Upvotes: 1