Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Vowel, other characters and consonant difference in a string JavaScript
We are required to write a function that takes in a string of definite characters and the function should return the difference between the count of vowels plus other characters and consonants in the string.
Problem Explanation
For example, if the string is:
"HEllo World!!"
Then, we have 7 consonants, 3 vowels and 3 other characters here so the output should be:
|7 - (3+3)| = 1
Hence, the output should be 1
Example
const str = 'HEllo World!!';
const findDifference = str => {
const creds = str.split("").reduce((acc, val) => {
let { v, c } = acc;
const vowels = 'aeiou';
const ascii = val.toLowerCase().charCodeAt();
if(!vowels.includes(val.toLowerCase()) && ascii >= 97 && ascii
Output
1
How It Works
The function works by:
- Splitting the string into individual characters
- Using
reduce()to count consonants (c) vs vowels + other characters (v) - Checking if a character is a consonant by verifying it's alphabetic but not a vowel
- Everything else (vowels and non-alphabetic characters) is counted in the 'v' category
- Returning the absolute difference between consonants and (vowels + other characters)
Alternative Implementation
const findDifferenceAlternative = str => {
let consonants = 0;
let vowelsAndOthers = 0;
const vowels = 'aeiouAEIOU';
for (let char of str) {
if (/[a-zA-Z]/.test(char) && !vowels.includes(char)) {
consonants++;
} else {
vowelsAndOthers++;
}
}
return Math.abs(consonants - vowelsAndOthers);
};
console.log(findDifferenceAlternative('HEllo World!!'));
Output
1
Conclusion
This function calculates the absolute difference between consonant count and the combined count of vowels plus other characters. Both implementations achieve the same result using different approaches - one with reduce() and another with a simple loop.
Advertisements
