Hi! I'm writing a function that counts all even numbers of an array, and it works pretty well, but, I don't know how to avoid counting empty strings or empty arrays as O while counting the number 0 as even. Here is my code:
function is_an_even_number(array){
var count = 0;
for(let i = 0 ; i < array.length; i++) {
if (array[i] % 2 === 0){
count++;
}
}
return count;
}
Also if you could help me improve the code, I believe there has to be a shorterand more efficient way to write this. I'll be really thankful.
This is how it should behave:
is_an_even_number([1,5,9,33,65,[],'',0,66,['banana']])
2
is_an_even_number(["100", 33, "Hello"])
1
And this is how it's working:
is_an_even_number([1,5,9,33,65,[],'',0,66,['banana']])
4
is_an_even_number(["100", 33, "Hello"])
1
//Solved! I'm just excluding empty strings and arrays with the && comparison:
function is_an_even_number(array){
var count = 0;
for(let i = 0 ; i < array.length; i++) {
if (array[i] % 2 === 0 && array[i] != "" && array[i] != []){
count++;
}
}
return count;
}
What I have tried:
function is_an_even_number(array){
var count = 0;
for(let i = 0 ; i < array.length; i++) {
if (array[i] % 2 === 0){
count++;
}
}
return count;
}
//Solved! I'm just excluding empty strings and arrays with the && comparison:
function is_an_even_number(array){
var count = 0;
for(let i = 0 ; i < array.length; i++) {
if (array[i] % 2 === 0 && array[i] != "" && array[i] != []){
count++;
}
}
return count;
}