Frequency of vowels and consonants in JavaScript


We are required to write a JavaScript function that takes in a string which contains English alphabets. The function should return an object containing the count of vowels and consonants in the string.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const str = 'This is a sample string, will be used to collect some data';
const countAlpha = str => {
   return str.split('').reduce((acc, val) => {
      const legend = 'aeiou';
      let { vowels, consonants } = acc;
      if(val.toLowerCase() === val.toUpperCase()){
         return acc;
      };
      if(legend.includes(val.toLowerCase())){
         vowels++;
      }else{
         consonants++;
      };
      return { vowels, consonants };
   }, {
      vowels: 0,
      consonants: 0
   });
};
console.log(countAlpha(str));

Output

The output in the console will be −

{ vowels: 17, consonants: 29 }

Updated on: 21-Oct-2020

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements