Counting number of vowels in a string with JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string. The function should count the number of vowels present in the string.

The function should prepare an object mapping the count of each vowel against them.

Example

The code for this will be −

const str = 'this is an example string';
const vowelCount = (str = '') => {
   const splitString=str.split('');
   const obj={};
   const vowels="aeiou";
   splitString.forEach((letter)=>{
      if(vowels.indexOf(letter.toLowerCase()) !== -1){
         if(letter in obj){
            obj[letter]++;
         }else{
            obj[letter]=1;
         }
      }
   });
   return obj;
};
console.log(vowelCount(str));

Output

And the output in the console will be −

{ i: 3, a: 2, e: 2 }
raja
Published on 24-Nov-2020 09:56:58
Advertisements