Vowel Count

Vowel Count

Vowel Count is counting the vowels (a,e,i,o,u) from string.

Example:
console.log(vowelCount(‘Emir Mustafoski’))
[object Object] { a: 1, e: 1, i: 2, o: 1, u: 1 }
console.log(vowelCount(“Natalie Portman”))
[object Object] { a: 3, e: 1, i: 1, o: 1 }

function vowelCount(str){
    var vowels = "aeiou";
    return str.toLowerCase().split('').reduce(function(acc,next){
        if(vowels.indexOf(next) !== -1){
            if(acc[next]){
                acc[next]++;
            } else {
                acc[next] = 1;
            }
        }
        return acc;
    }, {});
}

console.log(vowelCount('Emir Mustafoski'))
console.log(vowelCount("Natalie Portman"))

We create a function called vowelCount with parameter called str and variable calledd vowels that is equal to every vowel “aeiou”

We return str.toLowerCase().split(‘’).reduce(function(acc,next) {})
We turn str to lowercase with toLowerCase JavaScript Method nad than we use split(‘’) like this to turn that string into an array. then we chain reduce wich returns callback function with parameters acc and next

if(vowels.indexOf(next) !== -1){ we check if vowels with .indexOf another JavaScript Method
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. -MDN

Then we check
if(acc[next]){
acc[next]++;
} else {
acc[next] = 1;
}
return acc;


If acc[next] is vowel and if it is we increase with acc[next]++
else if it only found vowel once acc[next] = 1;
In the end we return the acc

comments powered by Disqus