Use Reduce Method To Analys(z)e Data, the best way of doing it?

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?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I also added [spoiler][/spoiler] tags since these are working solutions to curriculum challenges.

I like the first solution better. My only qualm is that nolanAvg is not an average, it is a total or a sum.

In the second one, yeah, they do the same filter twice. They should have that in a variable. You could argue that the map is not needed, but that is subjective. Really, you could do this with just a reduce. Some might argue that that would be less readable, but I think you could wrap the callback in a well named function and make it OK.