I was doing this lesson about Functional Programming in Javascript :
In the solution, it is written I have to recalculate how many movies are in the source array with Director : "Christopher Nolan" in order to calculate the average rating of theses movies.
It has come to my attention that the callback function of the reduce method has an optional array argument, so I wanted to use it to make the code leaner.
function getRating(watchList){
// Only change code below this line
var averageRating = watchList
.filter(element => element.Director == "Christopher Nolan")
.map(element => parseFloat(element.imdbRating))
.reduce((sum, val, index, array) => (sum+val)/array.length,0);
// Only change code above this line
return averageRating;
}
Unfortunately, it doesn’t work. Is it because the array that I’m trying to use correspond to watchList, or maybe have I made a mistake ?
reduce is an array method with works by iterating over each element over the array so in that “on each iteration, find the array.length and then divide it by the sum of the previous and the current rating”
so basically you need to find the average only once after youre done summing up the whole thing with reduce.
@staranbeer, you misunderstood my problem. I already know what this method is doing, but I want to understand why I can’t use the array argument of the callback function.
In the doc from Mozilla :
callbackFn
A function to execute on each element in the array (except for the first, if no initialValue is supplied).
It takes four arguments : accumulator
The accumulator accumulates callbackFn’s return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue , if it was supplied (see below). currentValue
The current element being processed in the array. index (Optional)
The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, it starts from index 1 . array (Optional)
The array reduce() was called upon.
This is precisely the array I’m interested in to put in use for my codebase.
yes because it would simply do the same thing over and over again for the each value in the array which is not what you want in this case. Glad i could help!