DEV Community

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

Posted on • Updated on

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

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 👍😊

Oldest comments (15)

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy 🎖️ • Edited
const vowelCount = sentence => [...sentence].reduce((a,v)=>a+[...'aeiou'].includes(v),0)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frontendengineer profile image
Let's Code

nice and sweet! thanks for the snippet.

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy 🎖️ • Edited
const vowelCount = sentence => ~~sentence.match(/[aeiou]/gi)?.length
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frontendengineer profile image
Let's Code

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.

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy 🎖️

One character more without the ~~

const vowelCount = sentence => sentence.match(/[aeiou]/gi)?.length||0
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

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.

Thread Thread
 
frontendengineer profile image
Let's Code

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

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

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

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

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

Thread Thread
 
frontendengineer profile image
Let's Code • Edited

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.

Thread Thread
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy 🎖️

Insults? No-one insulted anyone. I even apologised for being kinda off-topic

Collapse
 
ninjacoder199413 profile image
Ninja Coder • Edited

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

Collapse
 
russfraze profile image
Russell Fraze

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.

Collapse
 
frontendengineer profile image
Let's Code

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

Collapse
 
neillindberg profile image
neillindberg • Edited

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

Some comments have been hidden by the post's author - find out more