DEV Community

Discussion on: Find The Vowels used in a String with JavaScript

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

I know this is massively illegible compared to your beautifully constructed routine (which might well be how I'd write it because I'm all for legibility) but the short version might be coded as:

const count = str.split('').reduce((a,c)=>a + ("aeiouAEIOU".includes(c) ? 1 : 0), 0)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wulymammoth profile image
David • Edited

Yeah, this is no bueno. LOL.

For those trying to understand...

  1. str is the target decomposed into a character-array
  2. the a represents the accumulator in the callback that is initialized to be a counter of 0 which is at the end as the second argument to Array.prototype.reduce.
  3. the c represents the character (letter)
  4. the body of the callback reads as such -- a (accumulator/counter) + 1 if the character, c, is found, and 0 otherwise using a ternary operator expression.

I love Array.prototype.reduce, too, but this is not expressive LOL.

Using good variable names here is important IMO:

let str = "foobar", defaultCount = 0;

// reduces vowel look-up to O(1) compared to O(n) where n is the # of vowels
const vowels = new Set("aeiouAEIOU".split("")); 

str.split("").reduce((vowelCount, character) => {
  return vowelCount + (vowels.has(character) ? 1 : 0);
}, defaultCount); 
> 3