Tristanisha
Tristanisha

Reputation: 1

Counting vowels in a string JS

What is the best way to count each vowel separately in a string and display it as "A=0", "i=2", "e=1", and so on, case insensitively? I have this so far, but it doesn't count each symbol, only the total amount.

let arr_vowels = 'aeiouAEIOU'.split('');
let count = 0;
word.split('').forEach(function(e) {
    if (arr_vowels.indexOf(e) !== -1) {
        count++;
    }
});
                     
console.log(count);

Upvotes: 0

Views: 354

Answers (3)

Neil Gaetano Lindberg
Neil Gaetano Lindberg

Reputation: 2935

This includes a couple of "sometimes 'y'" situations which I think is more ideal. Not everything I just learned about special cases for "y" is covered. I can't seem to imagine how to tell when it is in the middle of a syllable like in "system", where the "y" should be included in the vowel count. Anyway, the below would return with matches for "gym" (1) and "my" (1), as well as "bay" (2).

// aeiou or y is at end, or if that didn't pass 
// we can check for only one "y" and that makes it a vowel too.
// also utilize the (g)lobal and case-(i)nsensitive flags on my regex.

const getVowelsCount = (sentance) => {
  const words = sentance.split(/\s+/gi);
  return words.reduce((accumulator, word) => {
    const count =
      word.match(/[aeiou]|y$/gi)?.length || word.match(/y{1}/gi)?.length || 0;
    return accumulator + count;
  }, 0);
};

Upvotes: 0

Nerdragen
Nerdragen

Reputation: 3174

Similar to the other solution, but simply with an object, you can do the following:

const vowels = {
    a: 0,
    e: 0,
    i: 0,
    o: 0,
    u: 0,
};
const str = "This is A test for counting vowels.";

str.split('').forEach((letter) => {
    const insensitiveLetter = letter.toLowerCase();
  
  if (vowels[insensitiveLetter] !== undefined) {
    vowels[insensitiveLetter] += 1;
  }
});

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163207

With the current approach, you are increasing the same count for a vowel.

One approach can be using a Map for example counting each vowel separately, and then loop the entries of the Map to get the key and value.

const vowels = 'aeiouAEIOU';
const str = "This is A test for counting vowels.";
const m = new Map();

for (let i = 0; i < str.length; i++) {
  let char = str[i]
  if (vowels.includes(char)) {
    !m.has(char) ? m.set(char, 1) : m.set(char, m.get(char) + 1);
  }
}

for (const [key, value] of m.entries()) {
  console.log(`${key} = ${value}`);
}

Upvotes: 1

Related Questions