Am I somewhere near the solution? I always get a double number of the consonants.
I was convinced that this was the correct approach.
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i <= str.length; i++) {
if (str[i] !== "a" || str[i] !== "e" || str[i] !== "i" ||
str[i] !== "o" || str[i] !== "u" || str[i] !== " ") {
countConsonants += 1;
}
}
return (countConsonants);
}
consonants("asdfghaaa");
I am expecting an answer of 5 i.e. sdfgh
are the consonants.
Your logic is flawed, The operator in your condition should be AND &&
not OR ||
, since you want to compare all the chars not just one of them :
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] !== "a" && str[i] !== "e" && str[i] !== "i" &&
str[i] !== "o" && str[i] !== "u" && str[i] !== " ") {
countConsonants++;
}
}
return (countConsonants);
}
console.log(consonants("asdfghaaa"));
NOTE : The loop should stop at length-1
since arrays are 0 based, so replace :
for (var i = 0; i <= str.length; i++) {
__________________^^
By :
for (var i = 0; i < str.length; i++) {
__________________^
Hope this helps.
The main problem in counts lies within your conditions.
You're increasing the number of consonants whenever one of the conditions fail (that's what ||
does, known as the OR operator). So whenever a character !== "a"
OR !== "e"
, you're increasing the count, which is wrong. (Imagine that a is !== 'e'
, so you're counting a as a consonant).
Change the ||
binary operator to &&
(AND); this way, you're only increasing the consonant count whenever the current character str[i]
is not among the values you're verifying for (a, e, i, o, u, ' ').
As others pointed out, you're also likely to run into an error as the max value of i should be Length-1.
There also other problems you need to consider:
For a beginner, this may not be relevant, but it's well worth getting these techniques under your skin: It's more readable to create an array that contains all of the value you're verifying for ["a","e", etc] and then, for each char in the source string, just verify if array.indexOf(str[i]) >= 0 (which means that the character is included in the array).
Your answer is almost right. The only problem is ||
instead of &&
. You're checking that it's not a AND it's not e AND it's not i, etc. Your function comes out true for every letter, since a is (not a || not e), right?
You can do
let str = 'asdfghaaa';
let result = str.split('').filter(e => e.match(/[^aeiou]/) != null).length;
console.log(result);
function consonants (str) {
return str.match(/[aeoiu]/gi)||[].length;
}
May be not good for long string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With