Use the reduce Method to Analyze Data

Use the reduce Method to Analyze Data
0.0 0

#1

I’m getting a different result I hope you could help me.

var averageRating = watchList.filter((elem) => elem.Director == "Christopher Nolan").reduce((sum, elem,currentIndx,array) => {
sum += Number(elem.imdbRating); // 34.7
return sum / array.length;
}, 0);

// Add your code above this line

console.log(averageRating);

What I get is 2.8062500000000004 which is wrong. I don’t know if it is a good idea to do return sum / array.length.


#2

To calculate an average, you must sum all the relevant data values first and then divide by the total number of relevant data values. You do not want to divide the sum each time by the the total number of relevant data values. The division should occur after the reduce has returned the final sum. The catch is, you will need to save that total number of relevant values somewhere to use after the reduce has returned the value based on your current solution.

Hint: Think about how the filtered array could used to get the count to use in the conjunction with the final sum the reduce returns.


#3

But when I tried to test return Number(sum) on that code it returns 34.7 which is fine. I also tried to change it to return Number(array.length) which is 4 and that’s fine too. Although when I test it with return sum / array.length it shows a number but different than expected. Could you please tell more what is exactly happening there? It seems it is not dividing the sum each time because when I tried it on the calculator it is different too.


#4

Like I said before, you are not calculating the average of the ratings. During each iteration of the reduce, you have the right idea to calculate the sum with sum += Number(elem.imdbRating), but you should not be dividing sum by array.length inside the reduce callback.

Currently, the filter returns an array with the 4 movie objects directed by Christopher Nolan. That is correct.

Then, takes this array of movie objects and starting with sum = 0, it adds the numeric value of elem.imdbRating back to the sum argument. That is correct.

Instead of just returning sum which would create the correct total of 34.7, your code is dividing each previous sum by 4 during each iteration. Put a console.log(sum/array.length) before the return statement and you will see what is getting returned for sum at the start of the next iteration.

Like I said previously, try performing the filter first and assign it’s result to a variable which you can use in a certain way (which you need to figure out by yourself) in the final calculation for the averageRating variable.


#5

Oh ok thank you. Now I undestand it.