I’m trying to solve this task –
“given a string, return the word with the highest score. The score can be calculated the following way:
- for each vowel, add +1 to the score ([“a”, “e”, “i”, “o”,
“u”, “y”]) - for each constant [“b”, “d”] substract 1 from the score
for example, “butterfly” will have the score of 2, we add +3 for each vowel (“u”,”e”,”y”) and substract 1 for constant (“b”). The word “day” will have score of 2 ( we add 2 for “a”,”y”). The function needs to return the word with the highest score.
This is my code so far:
function countVowels(string) {
let vowels = ["a", "e", "i", "o", "u"]
let constants = ["b", "d"]
let words = string.trim().split(" ")
let highestScore = " ";
let count =0;
for(const c of words){
for (let i=0; i<c.length; i++){
if(vowels.includes(c[i])) {
highestScore = c
count++;
}
else if (constants.includes(c[i])) count--
}
}
console.log(highestScore)
return highestScore;
}
countVowels("what a beautiful day")
The issue is that my code returns the last word in the sentence, not the word with the highest score. If I pass “what a beautiful day”, function returns “day” not “beautiful”. I can’t seem to find a way to return the correct value. Any advise and help is appreciated.