Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Last active October 18, 2022 16:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GreggSetzer/c1db8154c33b2385975089034d0a20ac to your computer and use it in GitHub Desktop.
Save GreggSetzer/c1db8154c33b2385975089034d0a20ac to your computer and use it in GitHub Desktop.
JavaScript Interview Question: Find all Vowels in a string
/*
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
//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