I need explanation for this please

Tell us what’s happening:
I did not understand where the rating parameter of the reduce function gets its value from?
.reduce((sumOfRatings, rating) => sumOfRatings + rating)
because in the example the property of the watchList obj is imdbRating.

Your code so far

function getRating(watchList){
  // Add your code below this line
  var averageRating =
  watchList
    // Use filter to find films directed by Christopher Nolan
    .filter(film => film.Director === "Christopher Nolan")
    // Use map to convert their ratings from strings to numbers
    .map(film => Number(film.imdbRating))
    // Use reduce to add together their ratings
    .reduce((sumOfRatings, rating) => sumOfRatings + rating) /
  // Divide by the number of Nolan films to get the average rating
  watchList.filter(film => film.Director === "Christopher Nolan").length;
  // Add your code above this line
  return averageRating;
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36

Challenge: Use the reduce Method to Analyze Data

Link to the challenge:

The reduce method takes two arguments

First: A callback to be executed on each iteration

Two: The starting value for the first element to the callback

This is known as the functions signature and it defines what the function expects to take in. The callback handed to reduce has a signature as well and that is how it knows how to call it. In the reduce methods case it takes a reducer function, and I will get into its signature and definition.

//I'm going to make a function that is 
//similar to the reduce method

function reduce (callback, reducerInitValue, arr) {
    if (reducerInitValue !== undefined) {
        let returnVal = reducerInitValue
        for (let i = 0; i < arr.length; i++) {
            returnVal = callback(returnVal, arr[i], i);
        }
        return returnVal;
    }

    let returnVal = arr[0];
    for (let i = 1; i < arr.length; i++) {
        returnVal = callback(returnVal, arr[i], i);
    }
    return returnVal;
}

//this is the callback
function reducer (initVal, element, index) {
    //do stuff
}

The reduce I have written is functionally similar to the reduce method and has a near identical signature: (callback, reducerInitValue, arr) although the arr part is an addition as this function is not a method of arrays.

The reducer is just the supplied callback to reduce and its signature:
(initVal, element, index) is needed for reduce to work as reduce expects a function with that signature so it knows how to call it.

What the callback actually does can be anything to nothing.

I did omit the last parameter to the callback, but it would have been arr if it did exist.

1 Like

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