I'm trying to make a JavaScript function that tells how many times a vowel was repeated in a given string.
Here's what I have tried:
function checkVowel(str) {
vowels = ['a', 'e', 'i', 'o', 'u']
str = "hello world"
for(let i = 0; i < str.length; i++){
if(str[i].includes(vowels)){
console.log("worked")
} else {
console.log("not worked")
}
}
}
checkVowel()
How can I make this function check for each vowel rather than the entire array at once?
Is it this what you're looking for?
function checkVowel(str) { const counts = Object.seal({ a: 0, e: 0, i: 0, o: 0, u: 0 }); for (let char of str) { counts[char.toLowerCase()]++; } return counts; } console.log(checkVowel("hello world"));
Another solution
function countVowel(word) { const vowels = ["a", "e", "i", "o", "u"]; const wordArray = word.split("").map((s) => s.toLowerCase()); const result = { a: 0, e: 0, i: 0, o: 0, u: 0 }; return wordArray.reduce((acc, curr) => { if (vowels.includes(curr)) { ++acc[curr]; } return acc; }, result); } console.log(countVowel("Angel"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.