Use the reduce Method to Analyze Data

function getRating(watchList) {
  // Only change code below this line
const averageRating = watchList
    // Use filter to find films directed by Christopher Nolan
    .filter(film => film.Director === "Christopher Nolan")
    // Use map to convert their ratings from strings to numbers
    .map(film => Number(film.imdbRating))
    // Use reduce to add together their ratings
    .reduce((sumOfRatings, rating) => sumOfRatings + rating) /
  // Divide by the number of Nolan films to get the average rating
  watchList.filter(film => film.Director === "Christopher Nolan").length;

So I recently completed the problems prior to this one where I learned about .map and . filter. But when it came to this question where they asked me to apply what I learned I couldn’t remember how to use them properly. Is that bad?

Also now that I have looked at the solution the process makes a lot of sense. I only have a question about the last line of code, how is the last line of code dividing to get the average? Is “.length” doing that?

The .reduce code is totaling all of the ratings and the .filter gives an array of all of the films so if you use .length it gives you the array length which is equal to the total number of films.

average = sum / number of datapoints

example:
if you have 3.5, 3.8 and 3.2
the sum is 10.5(.reduce) and you divide by 3(.length) and get the average which is 3.5.

1 Like

Ahhhhh thanks!! Makes sense

Also its probably better to come up with your own solution first then maybe look at other ways to solve the problem later. Because the above solution is kind of advanced and involves method chaining which I dont think was taught in the course.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.