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?
2 Answers 2
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"));
answered Feb 27, 2021 at 2:52
Thomas
12.8k1 gold badge16 silver badges31 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
DecPK
Perfect combination of
seal and for of loop. Learned something new.DecPK
But it fails if any charater is in upper case
Roarke
Now, I have been trying to display the number of times a vowel was repeated using string template literal but it's not working. Can you help me with that?
Thomas
@IshaanSharma Same game. Make a new question (don't mix multiple/different questions in one post), show what you've tried, what you got and what you expected. Even with my answer and your comment above, there's a dozen ways that you could have written this and a hundred things that could have gone wrong.
Roarke
Got it! Thought duplicates post aren't allowed.
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"));
answered Feb 27, 2021 at 3:34
DecPK
25.4k6 gold badges32 silver badges46 bronze badges
1 Comment
Thomas
What's your intention? Downwards compatibility? And since you already have it:
curr in result is quicker O(1) than vowels.includes(curr) O(n)lang-js
str[i].includes(vowels)=>vowels.includes(str[i]). You might also want to remove the hardcodedstr = "hello world"--call the function withcheckVowel("hello world")instead, so you can reuse the function for different strings.