Using filter() first then map() returns an empty array?

Tell us what’s happening:
Hello, I wonder when i used this code, why it was returning an empty array []

var filteredList = watchList
    .map(a => (
        {
            title: a.Title, 
            rating: a.imdbRating
        }
    ))
    .filter(e => e.imdbRating >= 8.0);

But if I used map() first then filter(), it works as expected

var filteredList = watchList
    .filter(e => e.imdbRating >= 8.0)
    .map(a => (
        {
            title: a.Title, 
            rating: a.imdbRating
        }
    ));

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

Link to the challenge:

In your first example, you’ve mapped the imdbRating to a completely new property, rating. So when you then filter by imdbRating, a now-nonexistent property…

1 Like

Oh, I think I know the reason. The first code did not work because it executed the map() first instead of filter(), so the filter() could not find the property “imdbRating” because it has been changed to “rating”. I mistakenly thought the javascript executed the filter() first then map(). Thank you for the help.

1 Like

When we chain functions, as you have with filter and map, they execute left to right. When we nest functions, the order is innermost out.

So, in your case, it went map then filter. You have it exactly right.

1 Like

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