Identical code behaving differently. Help!

Tell us what’s happening:
While revising, I completed a challenge only for it to be rejected understandably since there was a spelling difference between my answer and the challenges’ answer.

When I check the solution, I found the differences of my code vs solution code minuscule. So I went and made some modifications to my code only for it to return an empty array.

Code[a] is my first answer.
Code[b] is my revised answer which is returning an empty array
Code[c] is the solution.

This is a sort to deeply understand the fundamentals etc.

Q. May you please explain why is that, when I change the array.map key of Code[a] to Code[b]. An empty array is returned?
Please notice that Code[b] and Code[c] are identical except for the order of which they are executed.

FYI The key in question is the imdbRating key vs rating

Your code so far

//Code[a]
const filteredList = watchList
.map(({Title: title, imdbRating: imdbRating}) => ({title, imdbRating}))
.filter((item) => item.imdbRating >= 8.0)

//Code[b]
const filteredList = watchList
.map(({Title: title, imdbRating: rating}) => ({title, rating}))
.filter((item) => item.imdbRating >= 8.0)

Code[c]
const filteredList = watchList
  .filter(({ imdbRating }) => imdbRating >= 8.0)
  .map(({ Title: title, imdbRating: rating }) => ({ title, rating }))

Your browser information:

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

Challenge: Use the filter Method to Extract Data from an Array

Link to the challenge:

Take a closer look at the difference between Code[a] and Code[b] before arrays are filtered:

const filteredList = watchList
.map(({Title: title, imdbRating: rating}) => ({title, rating}))

map, for each element returns object having title and rating properties. At the next step, with filter, filtering function is expecting imdbRating property.

3 Likes

HI @P.Mat3 !

If you want a visual of what @sanity has brought up, temporarily comment out your filter function and see what is returned in the console.

const filteredList = watchList
.map(({Title: title, imdbRating: rating}) => ({title, rating}))
//  .filter((item) => item.imdbRating >= 8.0)

Then you can see why you are getting an empty array using filter.

1 Like

@jwilkins.oboe Thank you to the both of you. It’s these little mistakes that do not get repeated once I understand what I did wrong. Most times another set of eyes is better that one.

Until next time.

1 Like

Item is undefined
Hence empty array

There is difference between code [c] and b

Item is a place holder of the item being iterated through. Item is defined. BTW, this issue has been resolved. You can find the solution above.

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