Use reduce method to analyze data category

Tell us what’s happening:
I’ve been reading and playing in JSFiddle and I have a solution. But it doesn’t seem ‘elegant’. For example, why is ratingArr undefined after the first reduce is called?
Your code so far

function getRating(watchList){
  // Only change code below this line
  let result = [];
  let ratingArr = watchList.reduce (function(acc,elem) {
    if (elem.Director == "Christopher Nolan") {  
      acc.push(parseFloat (elem.imdbRating));
      return acc;
    }
  }, result);
  
  return (result.reduce(function(acc,elem) {
    return (acc+elem)  
  }))/result.length;

  // Only change code above this line
//  return averageRating;
}
console.log(getRating(watchList));

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 (’).

Ok thanks. This is my first post - didn’t know.

Paul

where do you have that it is undefined?

having your reduce have side effects is an anti-pattern, try making it doing the same thing without having side effects

You are basically trying to implement a filter method here. Why not simplify your code and just use the filter method on watchList to obtain all the movies where Christopher Nolan is the director. The result of the filter could be assigned to a variable named “nolanMovies” or whatever.

Then, you could apply the reduce method to this filtered array of movies and add acc to the rating of each movie. Thee are two catches:

  • You will need to initialize acc as some starting number (I will let you figure that out),
  • The ratings are strings, so you will need to figure out how to convert them into something that can be added because if you use the + operator on two strings, you will be concatenating them.

Thanks. I was attempting to do it all in one function.

It is all within the a single function (getRating). It can be done in a single reduce (if that is what you meant) but it is a bit more advanced and not necessarily as readable as using one additional higher order function (like filter) before the reduce. When you get your existing code working, I can DM you how it can be done with a single reduce.