- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Example
Following is the code −
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; if(val.toLowerCase() === val.toUpperCase()){ return acc; }; if(legend.includes(val.toLowerCase())){ vowels++; }else{ consonants++; }; return { vowels, consonants }; }, { vowels: 0, consonants: 0 }); }; console.log(countAlpha(str));
Output
This will produce the following output in console −
{ vowels: 17, consonants: 29 }
- Related Articles
- Arrangement of words without changing the relative position of vowel and consonants?
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- Removing last vowel - JavaScript
- Frequency of vowels and consonants in JavaScript
- Vowel gaps array in JavaScript
- Moving vowels and consonants using JavaScript
- Counting number of 9s encountered while counting up to n in JavaScript
- Validating alternating vowels and consonants in JavaScript
- Number of letters in the counting JavaScript
- Counting divisors of a number using JavaScript
- Counting adjacent pairs of words in JavaScript
- Implementing counting sort in JavaScript
- Counting matching substrings in JavaScript
- Reversing consonants only from a string in JavaScript
- Distance to nearest vowel in a string - JavaScript

Advertisements