How to use ES6 Array Functions In Javascript
In this method utilizing ES6 array functions such as filter and reduce, we split the string into an array of characters. Using filter, we extract consonants based on a defined condition and then return the count using reduce. This approach offers a succinct and modern solution for counting consonants in a string.
Example: Implementation to find number of consonants in a string using ES6 array functions.
function countConsonants(str) {
// Convert the string to lowercase to handle case insensitivity
str = str.toLowerCase();
// Use filter to get an array of consonants
const consonants = str.split('').filter(
char => 'bcdfghjklmnpqrstvwxyz'.includes(char));
// Return the count of consonants
return consonants.length;
}
// Example usage
const str = "Hello World";
console.log(countConsonants(str)); // Output: 7
Output
7
Time Complexity: O(n)
Auxiliary Space: O(n)
Find Number of Consonants in a String using JavaScript
In JavaScript, counting the number of consonants in a string can be achieved through various approaches. Consonants are the letters excluding vowels (a, e, i, o, u).
Examples:
Input : abcde
Output : 3
There are three consonants b, c and d.
Input : w3wiki portal
Output : 12
Table of Content
- Using Iterative Approach
- Using Regular Expressions
- Using ES6 Array Functions