Vowel, other characters and consonant difference in a string JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that takes in a string of definite characters and the function should return the difference between the count of vowels plus other characters and consonants in the string.

For example −

If the string is −

"HEllo World!!"

Then, we have 7 consonants, 3 vowels and 3 other characters here so the output should be −

|7 - (3+3)| = 1

Hence, the output should be 1

Let's write the code for this function −

Example

const str = 'HEllo World!!';
const findDifference = str => {
   const creds = str.split("").reduce((acc, val) => {
      let { v, c } = acc;
      const vowels = 'aeiou';
      const ascii = val.toLowerCase().charCodeAt();
      if(!vowels.includes(val.toLowerCase()) && ascii >= 97 && ascii <=122){
         ++c;
         }else{
            ++v
         };
         return {c,v};
      }, {
         v: 0,
         c: 0
   });
   return Math.abs(creds.c - creds.v);
}
console.log(findDifference(str))

Output

The output in the console will be −

1
raja
Published on 31-Aug-2020 06:34:45
Advertisements