Wouldn't be better not to use filter twice?

In solution 1 from guide to this step:

filter method is used twice inside the function:

function getRating(watchList){
  // Add your 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;
  // Add your code above this line
  return averageRating;

I kinda thought that it would be better to create a variable for such cases, my solution looks like this:

function getRating(watchList) {
  // Only change code below this line
  const filteredByDirector = watchList.filter(
      movie => movie.Director === 'Christopher Nolan'
  let averageRating = filteredByDirector.reduce(
      (acc, obj) => 
        acc + Number(obj.imdbRating), 0      
      ) / filteredByDirector.length;

  // Only change code above this line
  return averageRating;


I also skipped option to use mapping, not sure if that was a good idea.

1 Like

Yes, I would agree.

It is fine but I would use a more descriptive name for acc. What does acc represent in this case?

Also, you can solve this problem with a single use of reduce. It is not a pretty but was fun to attempt to do it (for learning purposes). If you want a challenge, try to make it look something like:

function getRating(watchList) {
  const averageRating = watchList.reduce( 
   // your code goes here.

  return averageRating;
1 Like

I agree, I just not always think about naming when it comes to every challenge step.
Something like sumOfRatings would be descriptive enough I guess.

I’ll try it, definitely need more practice with reduce.

Yes or just ratingsSum. Either would make it clear what it is accumulating.

1 Like