DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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 πŸ‘πŸ˜Š

Top comments (15)

Collapse
 
t0nyba11 profile image
Tony B

Another option...


const getVowelCount = (() => {

  // create a set of vowels once at startup
  const v = new Set([...'aeiouAEIOU']);

  // add up how many characters in the string are in the vowel set 
  return s => {
    for (var t = 0, i = s.length; --i >= 0; t += v.has(s[i]));
    return t;
  }

})();
Enter fullscreen mode Exit fullscreen mode
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 Author

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
 
ninjacoder199413 profile image
Ninja Coder • Edited on

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

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
Jon Randy • Edited on

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 Author

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 Author • Edited on

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
 
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
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy • Edited on
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 Author

nice and sweet! thanks for the snippet.

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

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await