-2

So I came up with this, though the counter is not working properly.

const stringVowel = ('hottentottententententoonstellingsbedrijfsacademie')

const letters = stringVowel.split('');

const numberOfVowels = arr => arr.map(num => {
    let counter = 0;
    if (num === 'a' || num === 'o' || num === 'u' || num === 'e' || num === 'i') {
    counter++
    }
    console.log(counter)
})

numberOfVowels(letters)
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • You're redeclaring `counter` on every iteration, so it will never be more than 1. You'll need to declare it outside the `map` call, but you should be using `forEach` and not `map` as it is since you're not using the returned array. see: [JavaScript: Difference between .forEach() and .map()](https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map) – pilchard Nov 08 '21 at 21:42

1 Answers1

0

One option is to use the string match method and provide a regular expression with all the vowels:

const withVowels = 'hottentottententententoonstellingsbedrijfsacademie';

const noVowels = 'wqdftzsqq';

function numberOfVowels(str) {
  return str.match(/[aeiou]/ig)?.length ?? 0;
}

console.log(numberOfVowels(withVowels));

console.log(numberOfVowels(noVowels));

Edit: Updated to a more robust solution based on comments

Nick
  • 16,066
  • 3
  • 16
  • 32