# Totally stuck on Use the reduce Method to Analyze Data

Totally stuck on Use the reduce Method to Analyze Data
0

#1

totally stuck on this one… i can get an array of numbers [ 8.8, 8.6, 9, 8.3 ] using the following:

``````let cnFilms = watchList.filter((val) => {
return val.Director === "Christopher Nolan";
});

let ratings = cnFilms.map((rating) => {
return Number(rating.imdbRating);
});
``````

Next, when I try to use reduce, I can get the sum of the array items (34.7) using this:

``````let averageRating = ratings.reduce((total, sum) => {
return total + sum;
});
``````

However, if i try to then divide the result by ratings.length, I get:

``````return total + sum / ratings.length;   //15.275000000000002
return (total + sum) / ratings.length;  //2.9093750000000003
``````

the only way I can get the correct figure, which doesn’t pass the test, is by returning the full sum, and then console.logging the returned sum / ratings.length:

``````let averageRating = ratings.reduce((total, sum) => {
return (total + sum);
});
console.log(averageRating / ratings.length);  //8.675

``````

What am I missing!?

EDIT:
I have now thought about it a bit more, and renamed the averageRating variable to just totalRating and then set the average rating variable to:

``````let averageRating = totalRating / ratings.length;
console.log(averageRating);  //8.675
``````

probably not the most elegant solution as some of the others shared in the above replies go way over my head at this stage, i’m happy for the moment to just understand whats happening and then once used to doing it a certain way, look into ways to write it in a more short-handed way!

Struggling with reduce(): Functional Programming: Use the reduce Method to Analyze Data
#2

It is always better to start a new topic when asking a question related to your specific code. If you want to comment or answer a thread’s original poster, then you would reply back to the original thread. Since your questions are specific to your solution, I moved your post to a new topic.