In this blog, we'll go over how to find the vowels in a string. This problem provided me with good practice using a for...of loop.
Problem
We are given a string and are asked to create a function that returns the number of vowels contained in the string. If there are no vowels in the string, then the function should return 0. Vowels are the characters 'a', 'e', 'i', 'o', and 'u'.
vowels('hello')
//will return 2
vowels('aardvark')
//will return 3
vowels('rkzlwmlz')
//will return 0
Approach
We know that we can iterate through a string, so a for...of loop would be useful here. As we go through the loop, we will increase a variable named count by 1 for each vowel we encounter in the string. It will not matter if the character is lowercase or not, so we will ensure our function accounts for that. In order to check if the string contains any vowels, we will check the string against an array of vowels.
Solution
function vowels(string) {
let count = 0;
}
We will increase count every time our loop encounters a vowel in the string.
function vowels(string) {
let count = 0;
const vowels = ['a', 'e', 'i', 'o', 'u'];
We use the vowels array to compare against the string.
function vowels(string) {
let count = 0;
const vowels = ['a', 'e', 'i', 'o', 'u'];
for (let char of string.toLowerCase()) {
}
}
We use a for...of loop to iterate through the string. We use the toLowerCase()
method to convert the string to lower case. This ensures that we can correctly match the vowels in the string to the vowels array.
function vowels(string) {
let count = 0;
const vowels = ['a', 'e', 'i', 'o', 'u'];
for (let character of string.toLowerCase()) {
if (vowels.includes(character)) {
count++;
}
}
}
We use a conditional that says if the current character in the string that we're checking with our loop is included in the vowels array, then increase count by one.
function vowels(string) {
let count = 0;
const vowels = ['a', 'e', 'i', 'o', 'u'];
for (let character of string.toLowerCase()) {
if (vowels.includes(character)) {
count++;
}
}
return count;
}
Lastly, we return count since the question asks for the number of times vowels appear in the string.
Resources
Stephen Grider's Algorithms and Data Structures Udemy Course
Top comments (1)
Looks like you are solving it with JS. I would use a more functional style:
It looks better to me, though yours is perfectly valid.