Counting occurrences of vowel, consonants - JavaScript

We are required to write a JavaScript function that takes in a string which contains English alphabet, for example ?

const str = 'This is a sample string, will be used to collect some data';

The function should return an object containing the count of vowels and consonants in the string i.e. the output should be ?

{ vowels: 17, consonants: 29 }

Understanding the Problem

To count vowels and consonants, we need to:

  • Iterate through each character in the string
  • Check if the character is a letter (not a space or punctuation)
  • Determine if it's a vowel (a, e, i, o, u) or consonant
  • Keep count of both types

Solution Using reduce()

The most efficient approach uses the reduce() method to accumulate the counts:

const str = 'This is a sample string, will be used to collect some data';

const countAlpha = str => {
    return str.split('').reduce((acc, val) => {
        const legend = 'aeiou';
        let { vowels, consonants } = acc;
        
        // Skip non-alphabetic characters
        if(val.toLowerCase() === val.toUpperCase()){
            return acc;
        };
        
        // Check if vowel or consonant
        if(legend.includes(val.toLowerCase())){
            vowels++;
        } else {
            consonants++;
        };
        
        return { vowels, consonants };
    }, {
        vowels: 0,
        consonants: 0
    });
};

console.log(countAlpha(str));
{ vowels: 17, consonants: 29 }

Alternative Solution Using for...of Loop

Here's a more straightforward approach using a for...of loop:

function countVowelsConsonants(str) {
    const vowels = 'aeiouAEIOU';
    let vowelCount = 0;
    let consonantCount = 0;
    
    for (let char of str) {
        if (char.match(/[a-zA-Z]/)) {  // Only count letters
            if (vowels.includes(char)) {
                vowelCount++;
            } else {
                consonantCount++;
            }
        }
    }
    
    return { vowels: vowelCount, consonants: consonantCount };
}

const testString = 'Hello World! 123';
console.log(countVowelsConsonants(testString));
{ vowels: 3, consonants: 7 }

How It Works

The solution works by:

  1. Character filtering: The condition val.toLowerCase() === val.toUpperCase() identifies non-letters (spaces, numbers, punctuation)
  2. Vowel detection: Uses includes() to check if the lowercase character exists in the vowels string
  3. Accumulation: The reduce() method maintains running counts in an accumulator object

Comparison of Methods

Method Readability Performance Use Case
reduce() Moderate Good Functional programming style
for...of High Excellent Simple, easy to understand

Conclusion

Both approaches effectively count vowels and consonants by filtering non-alphabetic characters and categorizing letters. The for...of loop is more readable, while reduce() offers a functional programming approach.

Updated on: 2026-03-15T23:18:59+05:30

596 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements