JS Coding Question #1: Count all vowels [3 Solutions]
Let's Code

Let's Code @frontendengineer

About: A fan of technology/innovation, software engineer, and a father.

Joined:
May 6, 2019

JS Coding Question #1: Count all vowels [3 Solutions]

Publish Date: Aug 25 '21
29 16

Interview Question #1:

Write a function that counts all vowels in a sentence❓🤔

If you need practice, try to solve this on your own. I have included 3 potential solutions below.

Note: There are many other potential solutions to this problem.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Code: https://codepen.io/angelo_jin/pen/zYzYdmQ

Solution #1: String match method

  • String.match method retrieves the result of matching a string against a regular expression.
function getVowelsCount(sentence) {
  return sentence.match(/[aeuio]/gi) ? sentence.match(/[aeuio]/gi).length : 0;
}
Enter fullscreen mode Exit fullscreen mode

Solution #2: for-of And regex

  • simple iteration checking every characters in a sentence using regex does the job.
function getVowelsCount (sentence) {
    let vowelsCount = 0
    const vowels = ['a', 'e', 'i', 'o', 'u']

    for (let char of sentence) {
        if (/[aeiou]/gi.test(char.toLowerCase())) {
            vowelsCount++
        }
    }

    return vowelsCount
}
Enter fullscreen mode Exit fullscreen mode

Solution #3: for-of AND Array includes

  • this is a good alternative instead of using solution above. Basically, replace regex test and utilize array includes instead.
function getVowelsCount (sentence) {
    let vowelsCount = 0
    const vowels = ['a', 'e', 'i', 'o', 'u']

    for (let char of sentence) {
        if (vowels.includes(char.toLowerCase())) {
            vowelsCount++
        }
    }

    return vowelsCount
}
Enter fullscreen mode Exit fullscreen mode

Happy coding and good luck if you are interviewing!

If you want to support me - Buy Me A Coffee

In case you like a video instead of bunch of code 👍😊

Comments 16 total

  • АнонимAug 26, 2021

    [hidden by post author]

    • Let's Code
      Let's CodeAug 26, 2021

      nice and sweet! thanks for the snippet.

  • АнонимAug 26, 2021

    [hidden by post author]

    • Let's Code
      Let's CodeAug 26, 2021

      thanks for the snippet. I tend to stay away from ~ though as it is not commonly used and is not readable.

      However, we can prolly ask if interviewer is interested on some fancy code and may receive a bonus point for it.

      • АнонимAug 26, 2021

        [hidden by post author]

      • Jon Randy 🎖️
        Jon Randy 🎖️Aug 26, 2021

        As for staying away from language features because they are 'not commonly used' - I personally think that is a terrible idea. We end up writing code for the lowest common denominator of understanding - something that can only result in code becoming unnecessarily verbose, devoid of elegance, and possibly efficiency (see your example above where you call match twice). It's the equivalent of writing versions of adult literature for slow readers. Dumbing down has its place, but should only be done where appropriate.

        Way too much emphasis is put on making things 'easy' for the developer.

        • Let's Code
          Let's CodeAug 26, 2021

          i see valid points here.

          í believe that it should be easy for developer as they will be iterating on codebase over and over which will always get my vote. let build tool over optimize as it is one of their main job.

          i would definitely improve the match example. didnt make it the most optimized version here however i mentioned it on the youtube video though. 😃😉 i would continue to post readable bits like this though to capture ALL level of skill as why I exist here, to be able to share to all level of experience

          • Jon Randy 🎖️
            Jon Randy 🎖️Aug 26, 2021

            let build tool over optimize as it is one of their main job

            This kind of thinking is also part of the problem. If everyone has this attitude, how will anything get any better? Who builds the build tools? Who will maintain them once the creators have passed on?

            An over reliance on perceived simplicity is very dangerous

            • Jon Randy 🎖️
              Jon Randy 🎖️Aug 26, 2021

              Sorry to vent all this on you, I know you're just trying to make tutorials for beginners :P

              • Let's Code
                Let's CodeAug 26, 2021

                no room for insults on this platform now. its a waste of energy and time rather than helpful.

                if you are expecting over optimized solutions on my post, im afraid you will not be seeing it here. please feel free to start one or find some other place that will matches your expectations, should be plenty.

                same thing can be said with over optimizing is dangerous. there should be a right balance.

                who should build the build tools you asked? anybody who wants to.

  • James Jiang
    James JiangJun 22, 2022

    Another option - Using array reduce method
    function getVowelsCount(str) {
    const vowels = ["a", "e", "i", "o", "u"];
    return str.split('').reduce((prev, ch, idx) => (vowels.includes(ch.toLowerCase())) ? prev + 1 : prev, 0);
    }

  • Russell Fraze
    Russell FrazeSep 28, 2022

    Really finding these tutorials helpful. On the second solution, there is an array of vowels thats not being used. Also, the char.toLowercase() does not seem to be needed because there is already the i in the regex.

    • Let's Code
      Let's CodeOct 1, 2022

      thank you! tutorials are meant to see some patterns that you can use for interviews. Arrays of vowels are used to compare it with the sentence. we loop over the sentence one by one which is assigned to variable char AND we need to transform it as lowercase as sentence may come up as HeLLo WORLD. we know that o and O is not equal. hopefully this makes sense. let me know if it didn't

  • neillindberg
    neillindbergMar 6, 2023

    Consider some "y". Thanks for the 10 react refresher samples. Been away a couple months and your tests really helped wake me up. Very much appreciated!!!

    // aeiou or y is at end, or if that didn't pass 
    // we can check for only one "y" and that makes it a vowel too.
    // also utilize the (g)lobal and case-(i)nsensitive flags on my regex.
    
    const getVowelsCount = (sentance) => {
      const words = sentance.split(/\s+/gi);
      return words.reduce((accumulator, word) => {
        const count =
          word.match(/[aeiou]|y$/gi)?.length || word.match(/y{1}/gi)?.length || 0;
        return accumulator + count;
      }, 0);
    };
    
    Enter fullscreen mode Exit fullscreen mode
Add comment