Functional Programming - Use the reduce Method to Analyze Data. Can find the sum but cannot find the average

Hello folks! I am have been able to find the sum of the ratings for all the movies directed by Christopher Nolan. But I am struggling to find the mean(average). I know that it can be found by dividing the sum by the total number of movies, which is four, but I do not know exactly how to do that.
This is my code so far.

function getRating(watchList) {
  return watchList.reduce((average, movie, index) =>  movie.Director === "Christopher Nolan" ? (+movie.imdbRating + average): average
  , 0);
}

PS: the best solution I can think of is dividing the sum by the last index. But I don’t know how to put that into code.

Any help would be appreciated. Thank you.

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:104.0) Gecko/20100101 Firefox/104.0

Challenge: Functional Programming - Use the reduce Method to Analyze Data

Link to the challenge:

I would not name the accumulator average since it is not an average at all. It is the sum of all the ratings for movies directed by Christopher Nolan.

Why do you think dividing the sum by the last index is the correct solution? For example, let’s say there were 10 movies in the list and 3 of them were directed by Christopher Nolan, would you divide the sum of the ratings by the last index (9) to create the average?

You are correct not to try and hard code 4 as the number to divide the sum by because your function should be able to handle any list of movies.

FYI - You do not only have to use reduce to solve this challenge. You just have to use reduce as part of the solution. It can be solved with only reduce, but it is probably easier to filter the list down the just Christopher Nolan movies first and then use the reduce method on those. That way, you have a direct way of getting the number 4 instead of hard coding it.

1 Like

Thank you.
This is what I was able to make as my final solution.


function getRating(watchList) {
  let filteredList = watchList.filter(movie => movie.Director === "Christopher Nolan")
  let sum = filteredList.reduce((sum, movie) => (+movie.imdbRating + sum), 0);
  let average = sum / filteredList.length;
  return average;
}