I sometimes wonder if the answers I give are right not in the sense of just being correct because they spit out the right answer but rather “is this the best way to do it?”. I’m concerned that I might be picking up bad habits early on.
For instance my answer to Use Reduce Method To Analyze Data is this:
function getRating(watchList) {
const nolanFilms = watchList.filter(user => user.Director == "Christopher Nolan");
const nolanAvg = nolanFilms.reduce((sum, film) => sum + parseFloat(film.imdbRating), 0);
return nolanAvg / nolanFilms.length;
}
The first solution in the hints is this:
function getRating(watchList) {
const averageRating = watchList
.filter(film => film.Director === "Christopher Nolan")
.map(film => Number(film.imdbRating))
.reduce((sumOfRatings, rating) => sumOfRatings + rating) /
watchList.filter(film => film.Director === "Christopher Nolan").length;
return averageRating;
}
Both of these work but the recommended solution uses 2 filters a map and a reduce. My solution uses two variables, 1 filter and a reduce and seems to me less complicated. Why is one better than the other?