-4

We have an array and we count a variable to +1 if number specific element found in an array. It gives an output 0.

Any help Why .?

let arr = ['a', 'b', 'c', 'a', 'a',];

 let a = 0;

if (arr === 'a') {
 return a = a + 1;
} else {
return 'Invalid'; 
}

//Output is 0
rayvic
  • 105
  • 2
  • 13

1 Answers1

0

You need to iterate the items of the array and check the value of it.

By taking the return statement, you exit the function, which is actually not given. More than that, you want to count the other 'a' as well.

let arr = ['a', 'b', 'c', 'a', 'a', ],
    a = 0,
    i;

for (i = 0; i < arr.length; i++) {
    if (arr[i] === 'a') {
        a = a + 1;
    }
}

console.log(a);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392