Last active
October 18, 2022 16:28
-
-
Save GreggSetzer/c1db8154c33b2385975089034d0a20ac to your computer and use it in GitHub Desktop.
JavaScript Interview Question: Find all Vowels in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Create a function to return the total number of vowels in a string. | |
Use String.prototype.match() to find matches | |
using a regular expression. | |
/[aeiou]/gi | |
// denotes a regex pattern. | |
[] instructs match() to find any of these characters. | |
g instructs match() to search globally in the string | |
and return all matches. | |
i instructs match() to be case insensitive. | |
String.prototype.match() returns an array of | |
matches or null when no match is found. We can | |
return the total count by using a ternary operator. | |
If matches() returns an array, this is | |
considered truthy, therefore, we return the length | |
of the array. If matches() returns null, this is | |
considered falsy, therefore, we need to return 0. | |
*/ | |
function vowel(str) { | |
const matches = str.match(/[aeiou]/gi); | |
return matches ? matches.length : 0; | |
} | |
//Try it | |
console.log(vowel('abcdefg')); // Returns 2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Find and return the word with the highest frequency of vowels in a string of text. | |
function vowels(str) { | |
//Create an object with key/value pairs containing word (key) and vowel count (value). | |
const wordMap = getVowelFrequencyMap(str); | |
//Use reduce as a comparator to return the word with the most vowels. | |
return Object.keys(wordMap).reduce((a,b) => wordMap[a] > wordMap[b] ? a : b); | |
} | |
//Helper function to get the character frequency. | |
function getVowelFrequencyMap(str) { | |
let map = {}; | |
str.split(' ').forEach(word => { | |
let matches = word.match(/[aeiou]/gi); | |
map[word] = matches ? matches.length : 0; | |
}); | |
return map; | |
} | |
//Try it | |
console.log(`Word with most vowels: ${vowels('Goodnight Moon')}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment