Reduce Method to Analyze Data. Why this code doesn´t work

Tell us what’s happening:

Reading tutorials I saw that you can use both reduce and filter in the same instruction so I thought combining:

var averageRating = watchList.reduce((acc, currValue) => {

return acc + Number(currValue.imdbRating)

}, 0).filter((currValue) => {return currValue.Director == 'Christopher Nolan'});

Similar code works for the guy that is doing the tutorial, I just changed the values for the ones required in the challenge. However the console gives error: TypeError: watchList.reduce(…).filter is not a function

What do you guys think I´ve missed? If i have missed a lot please don´t show me the solution yet then :grimacing:
Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.

Link to the challenge:

You want to call filter before reduce. You are currently chaning filter after reduce method, but reduce actually doesn’t return an array to be filtered. It returns a number in this case, your sum.

Great, thanks a lot. Now the function obvious gives me 34.7 which is just the sum and not the avg however.
Doing this would be cheating:
var definitiveAvg = averageRating/4

Do you think I can refer the “thing” that take the filter function, and do something like:

return acc + Number(currValue.imdbRating)  / event.length (which is watchList.director == Christopher Nolan)

I know that is no how to use event but idk something like that. Like I don´t really understand how event really works and if could be of use here

filter returns an array which will have a length. You could assign the return value of the filter to a variable (let’s call it christopherMovies) and then get christopherMovies’ length. Then use that length in the calculation when you return the result of using the reduce method on the christopherMovies array.

Basically, you will have two variables instead of one. The second variable will be averageRating.

1 Like

Done. That was neat! thx

It also can be done in one line, but the readability decreases, because of the complexity of the code. If two pieces of code achieve the same thing efficiency-wise, I will typically pick readability over conciseness.

1 Like