Use the reduce Method to Analyze Data - Parameter Use

Hi - Am trying to make sure I understand this and not just look for an answer…

Questions - To the parameters to filter() or ie reduce, map which are all somewhat similar. How do the parameter lists work?

  • Can you only use what is in the doc? element, index, array?
  • I assume you can use different / additional parameters? How does JS interpret which each parameter means? Do you need a specific order?
  • How with the ,0 (or other number) at the end do you initialize specific parameters?

Below - I think JS is thinking ‘‘totalRatings’’ is the index it’s on… So, the prints out are adding the rating in the element to the index value… which of course is not what I want. Where is the error please for it to treat that as an accumulative total I want to add to?

For finding the average - can i use nolan.length?.. or I think /x.length after the ,0 in other examples online.

Thanks,
Brett

var nolan = watchList.filter(movie => {return movie.Director=="Christopher Nolan"})

// console.log(JSON.stringify(nolan));

var averageRating = nolan.filter((element, totalRatings) => {
  // console.log(JSON.stringify(element));
  console.log(totalRatings);
  totalRatings += Number(element.imdbRating);
  console.log(totalRatings);
  return totalRatings/nolan.length;
},0);

I think I’m using the => Wrong.

But if I try spelling it out a bit more… ie:
function(totalRatings, element)

The code editor seems to think totalRatings is the object, element is a number… :frowning:

They are not that similar. filter() expect a Boolean from the callback function, and returns an array containing only the elements for which the callback returned true (excluding those for which the callback function returned false).
In the first case you use filter correctly, but in the second one you are trying to make operations inside the filter method, it will not work.
You may want to read again on what those methods do, and use a different one for that.



k thanks. I will re-read

I saw this :
const average = euros.reduce((total, amount, index, array) => {
total += amount
return total/array.length
} , 0 );

at https://medium.freecodecamp.org/reduce-f47a7da511a9 as example guide…

reduce() and filter() are not the same thing, in your code you use only filter() and never use reduce()

holy COW!!! I am using .filter and not .reduce… R#@($#@()$*(@)#$@)(#$I. Thanks.

Thanks. Now working. Can’t believe how long i sat on that using the wrong function!

Hi ~
I got a lot of help here, and I was able to understand how it works by implementing filter and reduce functions directly.

But still “this” part is so hard that I still need more study.:sweat_smile:

resource : https://youtu.be/UXiYii0Y7Nw