Use the reduce Method to Analyze Data - what's wrong?

Hello guys!
Where I made a mistake?
It is printing “8.88.698.3”
Thank you,
Kuba

var filterByNolan = watchList.filter(function(item){
  return item.Director == "Christopher Nolan"
});

var ratingList = filterByNolan.map(function(element){
  var rating = [];
  rating.push(Number(element.imdbRating));
  return rating;
});

var averageRating = ratingList.reduce(function(prev, next){
  return prev + next;
});
console.log(averageRating);

There’s a few things that are going on here.

var ratingList = filterByNolan.map(function(element){
  var rating = [];
  rating.push(Number(element.imdbRating));
  return rating;
});

In the code above your are returning an array for each time you loop with the map function. The results will be something like [[8.8], [8.6], [9], [8.3]]. Its looks like the default behaviour of performing an add on arrays is to concatenate the results into a string.

You need to fix your map so that it returns a number for each iteration not an array:

var ratingList = filterByNolan.map(function(element){
  return Number(element.imdbRating);
});

Hint: Your could do all this in one reduce function. On each iteration of reduce you can check the item.director.

Also at the end you will need to divide the total by the array length.

But I have to store map results in some empty array. Your fix is not working :confused:
How to do it so in the end will be [8.8, 8.6, 9, 8.3]?

Here is the link to challenge CHALLENGE BETA

I wrote “Nolsan” in filter function… That’s why it didn’t work :grin:

var filterByNolan = watchList.filter(function(item){
  return item.Director == "Christopher Nolan"
});

var ratingList = filterByNolan.map(function(element){
  return Number(element.imdbRating);
});

var averageRating = ratingList.reduce(function(prev, next){
  return prev + next/ratingList.length;
},0);
console.log(averageRating);

Thank you randelldawon, your advice have help me through many challenges.

Just to note, when I went through this challenge, it is important to call reduce() with a initial value of 0. Otherwise, it assumes that the accumulator is an array.

The reduce method accepts these params, preValue, currValue, index.

If you provide an initial value, then preValue will be equal to that.

If you do not provide an initial value, then preValue will be the value of the first item in the array the method was called on.

Ex:

/* 
*  No initial value
*  prev -> 1 
*  curr -> 2
*/
[1, 2].reduce((prev, curr) => {})

/* 
*  Initial value
*  prev -> 0 
*  curr -> 1
*/
[1, 2].reduce((prev, curr) => {}, 0)