Use the reduce Method to Analyze Data: What isn't my code accepted?

I am completing the ‘Use the reduce method to analyze data’ task. Task:

The variable watchList holds an array of objects with information on several movies. Use reduce to find the average IMDB rating of the movies directed by Christopher Nolan . Recall from prior challenges how to filter data and map over it to pull what you need. You may need to create other variables, and return the average rating from getRating function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations.

My code:

function getRating(watchList) {
  let averageRating;

const filmByNolan = watchList.filter(film => film.Director == 'Christopher Nolan').reduce((sum, fil) => {
let me = Number(fil.imdbRating);
return sum + me;
}, 0);

averageRating = filmByNolan / 4;

}
console.log(getRating(watchList));

The only condition my code fails on is the following, & I don’t know why? :

Your code should return the correct output after modifying the watchList object.

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36

Challenge: Use the reduce Method to Analyze Data

Link to the challenge:

Where is this ‘magic number’ 4 coming from?


I’m confused by the overall structure of your code. I would expect something like

const myFilteredData = watchList.filter(/* ... */);
const myReducedData = myFilteredData.reduce(/* ... */);

I don’t understand why you have something of the form

const myFilteredAndReducedCombo = watchList.filter( /* something with reduce */);

Thanks for the reply. It asks for the average. There are 4 movies directed by Christopher Nolan.

Always and forever? Only 4 will be created in the history of the universe and every list of films will always have those 4?

2 Likes

Hi, I have corrected my code, & it’s passed the conditions now. Hopefully, my code is easier to read, as well. Thanks !

Code now:

function getRating(watchList) {
  // Only change code below this line
  let averageRating;
const filmByNolan = watchList.filter(film => film.Director == 'Christopher Nolan')
const filmsAfterRed = filmByNolan.reduce((sum, fil) => {
let me = Number(fil.imdbRating);
return sum + me;
}, 0);

const noOfFilms = filmByNolan.length;
averageRating = filmsAfterRed / noOfFilms;

  // Only change code above this line
  return averageRating;
}
1 Like