DEV Community

Muhammad Hamza Hijazi
Muhammad Hamza Hijazi

Posted on

JavaScript Programming Problem 2

JavaScript Programming Problems Series

I started Programming test series where i will be sharing share commonly asked interview questions and my solution for JavaScript developers .

Problem # 2

Count the number of individual vowels in a given string

you are given a string, count and return the number of vowels used in that string. for example if string has a four times and e two times it must return

{ 
   a:4,
   e:2 
 } 
Enter fullscreen mode Exit fullscreen mode

My Solution

const vowelCount = (str)=>{
    str = str.toLowerCase().split("");
    const vowel = "aeiou";
    const obj = {}

    for(let wo of str){
    if(vowel.indexOf(wo) !== -1){
        if(obj[wo]) {
        obj[wo] ++
        }
        else {
        obj[wo] = 1
        }
      }
    }


return obj
}

vowelCount("3123dasds JJKH e o a eee iJ")
Enter fullscreen mode Exit fullscreen mode

Share your possible solution

Top comments (5)

Collapse
 
pengeszikra profile image
Peter Vivo

I learn from wise guy: fun-fun-function reduce is a swish knife of functional programming, in this case:

[..."3123dasds JJKH e o a eee iJ"].reduce( 
 (coll, chr) => coll[chr] 
   ? {...coll, [chr]: coll[chr] + 1} 
   : {...coll, [chr]:1 }
, {});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hijazi313 profile image
Muhammad Hamza Hijazi

this function is counting all alphabets in string.

Collapse
 
pengeszikra profile image
Peter Vivo

you right!

to work with vowels need filter before this process:


const countChars =  
 (coll, chr) => coll[chr] 
   ? {...coll, [chr]: coll[chr] + 1} 
   : {...coll, [chr]:1 };

const vowels = "aeiouóöőüúűáé"; // hungarian vowels included

const filterWovels = chr => vowels.indexOf(chr) > -1;

const vowelCount = s => [...s.toLowerCase].filter(filterWovels).reduce(countChars, {});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
const vowelCount = s=>[...'aeiou'].reduce(
   (a,x)=>(c=(s.match(new RegExp(x,'gi'))||[]).length,{...a,...c&&{[x]:c}}),{}
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hijazi313 profile image
Muhammad Hamza Hijazi • Edited

Perfect <3