Functional programming with reduce() method

Tell us what’s happening:

I am just wondering why do we have to return the accumulator parameter ({sum, count}) if the last statement in the function is false (idx === arr.length -1 ) ?

Your code so far


function getRating(watchList) {
  
  const averageRating = watchList.reduce(({ sum, count }, { Director: dir, imdbRating: rating },  idx, arr) => {
    if (dir === 'Christopher Nolan') {
      count++;
      sum += Number(rating);
    }
    return idx === arr.length - 1
      ? sum / count
      : {sum, count};
  }, { sum: 0, count: 0 });
  
  return averageRating;
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36.

Challenge: Use the reduce Method to Analyze Data

Link to the challenge:

If the expression evaluates to false, you just need to return the current value of sum and current value of count. Otherwise, the next iteration would not have the correct values of the variables. It is only when you are in the last iteration (where idx === arr.length -1), that you actual calculate the average based on the final values of sum and count.

1 Like