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

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.