1
const arr2 = ['', '', '', ''];

I made a function using reduce method that returns the number of element when i put a array and a element into the function as arguments . like below.

    function count(array, element) {
      return array.reduce((count, value) => {
        if (value === element) {
          count++;
        }
        return count; 
      }, 0);
    }
    result = count(arr2, '');
    console.log(result);               

output

2

and it worked well. no problem till here.

but, i wanted to make it shorter using ternary operators.

but it doesn't work.

so i converted it trying my best. like below.

    function count(array, element) {
      return array.reduce((count, value) => value === element ? count++ : count, 0);
    }
    result = count(arr2, '');
    console.log(result);

output

0

how can i fix it?

bishop2
  • 11
  • 2
  • 1
    You're using `++` as post-increment operator. So it first reads and returns the value of `count` and only then increments the value. So `count` will always be `0`. Use `++` as pre-increment operator or just return `count + 1`. – Andreas Oct 29 '22 at 11:13
  • A better way is to `filter` and return the `length`, like this: `const count = (array, element) => array.filter(i => i === element).length;` – Harrison Oct 29 '22 at 11:18
  • @Harrison _"better"_ is subjective. There's nothing wrong (besides the wrong operator) with OPs script. – Andreas Oct 29 '22 at 11:19
  • @Andreas true, but OP wanted something more akin to a one-liner. They were incrementing a value, which is unnecessary in the way they needed it. – Harrison Oct 29 '22 at 11:21

0 Answers0