## DEV Community is a community of 888,741 amazing developers

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

Posted on

# 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
}
``````

## 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")
``````

## Discussion (5)

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 }
, {});
``````

this function is counting all alphabets in string.

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, {});
``````
Jon Randy • Edited on
``````const vowelCount = s=>[...'aeiou'].reduce(
(a,x)=>(c=(s.match(new RegExp(x,'gi'))||[]).length,{...a,...c&&{[x]:c}}),{}
)
``````
Muhammad Hamza Hijazi • Edited on

Perfect <3