Javascript: function to populate object with vowels as keys and counter as values
As before, I went through everything for an answer and I am just a beginner and I try to learn from this, not just provide an answer.
var voweler = function (str) {
var strArr = str.split('')
var obj = {};
for (var i = 0; i < strArr.length; i++) {
if (strArr[i] == 'a') {
obj.a = 0;
obj.a++;
} else if (strArr[i] == 'e') {
obj.e = 0;
obj.e++;
} else if (strArr[i] == 'i') {
obj.i = 0;
obj.i++;
} else if (strArr[i] == 'o') {
obj.o = 0;
obj.o++;
} else if (strArr[i] == 'u') {
obj.u = 0;
obj.u++;
}
};
return obj;
}
voweler("This is a test")
//returns this which is wrong. Object {i: 1, a: 1, e: 1}
+3
source to share
4 answers
Your code for updating counters is incorrect. Every vowel you encounter, you launch obj.<vowel> = 0
that clears the score! To fix this, set the counters before introducing the for loop and then in the for loop, only increment the counter.
If you prefer to only have an entry if the vowel exists, you can conditionally increase:
if(strArr[i] == <some_vowel>){
if(obj.<some_vowel> === undefined)obj.<some_vowel> = 1;
else obj.<some_vowel> ++;
}
+2
source to share
A few tips:
- Your loop sets the property value for the key to 0 every time the character is a vowel, before incrementing.
- You can use toLowerCase () if you want to find upper and lower case vowels.
- You can use
indexOf
. It will return -1 if it cannot find the argument in the string.
var voweler = function (str) {
var strArr = str.toLowerCase().split('');
var obj = {};
strArr.forEach(function(ch) {
if ('aeiou'.indexOf(ch) !== -1) {
obj[ch] = (obj[ch] || 0 ) + 1;
}
});
return obj;
}
console.log(voweler("This is a test"));
// Object {i: 2, a: 1, e: 1}
+2
source to share
Just because we can ... and DTing already has your answer.
function countVowels(s) {
var vowels = /[aeiou]/,
o = {};
s.toLowerCase().split('').forEach(function(c){
if (vowels.test(c)) o.hasOwnProperty(c)? ++o[c] : o[c] = 1;
});
return o;
}
console.log(JSON.stringify(countVowels('hi there')));
There is also:
function countVowels(s) {
return (s.toLowerCase().match(/[aeiou]/g) || []).reduce(function(o, c) {
o[c] = (o[c] || 0) + 1;
return o;
}, {});
}
0
source to share