Correct output but doesn't pass test

The function returns the correct result but it doesn’t pass the Your code should return the correct output after modifying the `watchList` object. condition.

function getRating(watchList) {
  // Only change code below this line
  let nums = []
  let averageRating = watchList.map(function(a) {
      if (a.Director === 'Christopher Nolan') {
          return a.imdbRating
      }
  }).forEach(str => {
      nums.push(Number(str))
  })

   nums = nums.slice(0, 4)
   return nums.reduce((a, b) => a + b) / nums.length
  // Only change code above this line
}

console.log(getRating(watchList));

Why? Your 'magic number ’ should be suspicious.

Why? Map to what you need.

Idk what you meant by the second one but I removed the hardcoded first line to nums = nums.filter(a => Boolean(a)) and it passed, so thank you.

You hard coded the number 4 in there. But that ‘magic number’ 4 means your function only works when there are 4 entries to average.

You shouldn’t need ‘nums’ at all. Why not use this output here let averageRating =...

Yes, I did fix that, I just don’t know what you meant by “Map to what you need”

You do not need a separate nums array. map makes an array. Make your map + filter make what you need instead of abandoning the result of the map… You never use the averageRating variable. That’s an indicator that something is strange.

Alright, I made these changes

function getRating(watchList) {
  // Only change code below this line
  
  let averageRating = watchList.map(function(a) {
      if (a.Director === 'Christopher Nolan') {
          return Number(a.imdbRating)
      }
  })

   averageRating = averageRating.filter(a => Boolean(a))
   return averageRating.reduce((a, b) => a + b) / averageRating.length
  // Only change code above this line
}
1 Like

That’s what I was trying to get at. You cn arrange that logic in a few ways - I think it’s worth looking at the possible solutions listed with the hints for this challenge.

1 Like