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;
}

console.log(getRating(watchList));

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

2 Likes

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.

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