Confused about this reduce method excercise

I’m doing Javascript pt1, Arrays 21, exercise 5, ‘count occurrences’. I am confused about the result of the .reduce solution to the problem.

Here's the relevant code...

const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];

const count = countOccurrences(numbers, 4);

console.log(count);


function countOccurrences(array, searchElement) {
  return array.reduce((accumulator, current) => {
    const occurrence = (current === searchElement) ? 1 : 0;
    return accumulator + occurrence;
  }, 0);

}

I don’t understand why accumulator + occurrence produces the correct count of an element. My array has four 4s and the function returns that result. So I decided to log the results of accumulator only and occurrence only, I got 0 and 1 respectively. I don’t understand why added together they make four.

Can anyone help me understand how this works?

Thanks.

The function you supply as the first argument to reduce() is called for every item in the array it is called on. reduce() calls your function with two arguments on each invocation:

  • accumulator: the value of the second argument to reduce() (here 0) on the first invokation or the result of the former invokation on each subsequent call
  • current: the value of the current array element.

So on the first invokation your function receives 0 (initial value) and 1 (first array item) as arguments. It then computes occurence to be 1 if the second argument is equal to the value we’re looking for or 0 otherwise. So on the first invocation it’s 0 and your function returns 0 + 0 which is 0.
On the second call your function receives 0 (the result of the last call) and 2 (the value of the second item) and also returns 0.
[…]
On the seventh call the arguments are 0 (the result of the last call) and 4 (the value of the seventh element). Now occurence evaluates to 1 since 4 is equal to the value we search for and the returned value is 1 (0 + 1).
On the eights call the arguments are 1 (the result of the last call) and 4 (the value of the eights element) and the returned value is 2 (1 + 1).
And so on and so forth…

So at the last call accumulator is 3 (from previous calls) and occurrence is 1 from the last round and they make 4?

I think I have it, might help to console.log each round so I can visualize. Thanks Sam.