'freeCodeCamp Challenge Guide: Use the reduce Method to Analyze Data
I am in the freeCodeCamp Use the reduce Method to Analyze Data challenge.
I tried:
function getRating(watchList){
// Add your code below this line
var count = 0;
var sum = 0;
var averageRating = watchList.reduce(function (obj) {
if (obj.Director === "Christopher Nolan") {
count++;
sum = sum + parseFloat(obj.imdbRating);
}
return sum;
}, 0) / count;
// Add your code above this line
return averageRating;
}
The result is NaN, what I am doing wrong? I must use the arrow function, because standard function declaration produced unexpected results?
Thanks for help
Solution 1:[1]
I will give you hint.
const res = watchList.filter((d) => d.Director === 'James Cameron').map(x => x.averageRating));
Then another map to Numbers
res.map(Number)
Now use reduce to calculate average of numbers. Everything is explained here.
Solution 2:[2]
you can try:
const relevant = watchList.filter(movie => movie.Director === "Christopher Nolan");
const total = relevant.reduce((sum, movie) => sum + Number(movie.imdbRating), 0);
const average = total / relevant.length;
or combine the last 2 lines:
const relevant = watchList.filter(movie => movie.Director === "Christopher Nolan");
const average = relevant.reduce((sum, movie) => sum + Number(movie.imdbRating), 0) / relevant.length;
Solution 3:[3]
function getRating(watchList){
// Add your code below this line
var titles = watchList.filter(function(obj){
return obj.Director === "Christopher Nolan";
});
//message(titles);
var averageRating = titles
.reduce( function(sum,obj){
return sum = sum + parseFloat(obj.imdbRating);
}, 0)/titles.length;
//message(watchList.Director);
// Add your code above this line
return averageRating;
}
Solution 4:[4]
let averageRating = watchList
.filter(movie => movie.Director === "Christopher Nolan")
.map(movie => Number(movie.imdbRating))
.reduce((sum, movie, index, arr) => ((movie/arr.length)+ sum), 0);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Richard Rublev |
Solution 2 | eamanola |
Solution 3 | ?ukasz Zadworny |
Solution 4 | Rustin McClure |