Use the reduce Method to Analyze Data -- Is this solution elegant?

I have solved the excercise “Functional Programming: Use the reduce Method to Analyze Data”. This is my code (only the ‘getRating’ function):

function getRating(watchList){
  // Only change code below this line
  var totalCount, totalSum, nolanMovs

  nolanMovs = watchList.filter(movie => movie.Director == "Christopher Nolan")

  totalCount = nolanMovs.length

  totalSum = nolanMovs.reduce((sum, movie) => sum + parseFloat(movie.imdbRating), 0)

  // Only change code above this line
  return totalSum / totalCount;

I should want to know if this solution is a correct way to solve the problem.


If it works, it is correct. As a challenge, see if you can only use the reduce method without the filter. So basically you would have something like:

function getRating(watchList){
  return watchlist.reduce((a, b, c) => /* some code here */ );
1 Like