1

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?

3
  • 1
    str[i].includes(vowels) => vowels.includes(str[i]). You might also want to remove the hardcoded str = "hello world"--call the function with checkVowel("hello world") instead, so you can reuse the function for different strings. Commented Feb 27, 2021 at 2:28
  • Do you want to count the number of occurrences for each vowel, or how many vowels there are in total in that string? Commented Feb 27, 2021 at 2:43
  • The first one actually. Commented Feb 27, 2021 at 2:51

2 Answers 2

4

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"));

Sign up to request clarification or add additional context in comments.

5 Comments

Perfect combination of seal and for of loop. Learned something new.
But it fails if any charater is in upper case
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?
@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.
Got it! Thought duplicates post aren't allowed.
0

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"));

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.