FUCTIONAL: Use the reduce Method to Analyze Data

FUCTIONAL: Use the reduce Method to Analyze Data
0

#1

The chalenge
Result must be 8.675. But i have 8.667. Whats wrong???

var averageRating = watchList                        
                            .filter(obj => obj.Director == 'Christopher Nolan')
                            .map((obj) => (Number([obj.imdbRating])))
                            .reduce((currV, nextV, indV) => ((currV + nextV) / indV+1)).toFixed(3);

#2

Your reduce function doesn’t undo the previous average calculation before taking the next average. You’ll need to do something with currV before adding nextV to it.

Also, you probably meant / (indV+1), not / indV+1.


#3

I don’t think so, bacause:
" .reduce((currV, nextV, indV) => (currV / indV + nextV / indV) + 1).toFixed(3); " //output=>8.667
" .reduce((currV, nextV, indV) => (currV / indV + 1 + nextV / indV)).toFixed(3); " //output=>8.667
The problem is exactly in " / indV+1 " in dividing “sum of curr & next”.
Another way is:
" … => currV + nextV) / watchList.filter(obj => obj.Director == ‘Christopher Nolan’).length; " //output=>8.675
The las example is wright solution :slight_smile:
BUT I can’t understand in what is difference, and why it exactly 0.008 ???


#4

var averageWright = watchList
.filter(obj => obj.Director == ‘Christopher Nolan’)
.map((obj) => (Number([obj.imdbRating])))
.reduce((currV, nextV) => currV + nextV) / watchList
.filter(obj => obj.Director == ‘Christopher Nolan’).length;
// Output 8.675

var averageWrong = watchList
.filter(obj => obj.Director == ‘Christopher Nolan’)
.map((obj) => (Number([obj.imdbRating])))
.reduce((currV, nextV, indV) => (currV + nextV) / indV+1).toFixed(3);
// Output 8.667


#5

Yeah, just reducing for the sum, then dividing by number of items is easier to understand. You could improve this by storing the filtered+mapped array first in a variable, then performing the reduce on that variable. That way you don’t need to filter twice.