Functional Programing - Use the reduce Method to Analyze Data

Hello everyone!

I am working in the JavaScript module in the functional programming section where I have to write code that returns an array with a specific write and an average rating. I have been looking at different resources, such as our good friends Google and ChatGPT. I always try to don’t get the answer right away from ChatGPT since obviously, I want to understand programming more and more, so, I would love some help here to know what I am missing.

Again, instead of the right code, I would like to know what part I should focus to fixed. I hope it makes sense.

Thank you Dev Friends!!

function getRating(watchList) {
  // Cambia solo el código debajo de esta línea
  let averageRating = watchList.filter((movies) => movies.writer === "Christopher Nolan")
  .filter((movies) => movies.imdbRating !== undefined);
  let newArray = averageRating.map((movies) => {
    return {
      director: movies.writer,
      rating: parseFloat(movies.imdbRating)
    };
  });

  if(newArray > 0) {
    let aveRate = newArray.reduce((sum, movies) => sum + movies.rating, 0) / newArray.length;
    console.log(aveRate);
  }else{
    console.log('No good rating');
  }

  // Cambia solo el código encima de esta línea
  return averageRating;
}

console.log(getRating(watchList));```

Can you explain what your code is doing?

You are creating a bunch of variables but using them inconsistently.

What the code should do is to return a filtered array with only the movies of that director (Christopher Nolan) and an rating average of those movies.

Here are the instructions of this.

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.

Please don’t copy-paste the instructions at me. I can read them.

Can you go into more detail? What do you think each line does, is order?

I see you are pretty close, but there are 3 problems:

  1. why writer? there are other properties…
let averageRating = watchList.filter((movies) => movies.writer === "Christopher Nolan")
  1. To check if the array is empty… Is this good way? or some other practice?
 if(newArray > 0)
  1. I see your use array.reduce() method correctly. But what should you return in the end? An array or a number?
return averageRating;

Happy coding…

1 Like

Awesome!! Thank you so much my friend for that guidance. I will keep working on this.

And coding is cool!!:sunglasses:

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