Question about .filter() to extract data from an array

Hello everyone! I’m currently on the challenge ’ Functional Programming: Use the filter Method to Extract Data from an Array’ and I have a question about the code.

I’m supposed to filter the data to return only movies with a rating above or equal to 8.0 and here is the code I came up with:

watchList.filter((movie) => {
  if (movie.imdbRating > 8.0) {
    return filteredList.push({
      title: movie.Title,
      rating: Number(movie.imdbRating),
    });
  }
});

My code above works perfectly and when I open my browser only movies with a rating above or equal to 8.0 show up (4 movies total) however, my code does not pass all of the tests. The results in the fCC console has an array filled with [object, object]. Can anyone tell me why I’m getting this result?

Thank you in advance and happy coding!

Never mind, I figured it out! The code editor didn’t like that I was changing the rating into a number. I removed the Number() statement and now the below code passes the tests:

watchList.filter((movie) => {
  if (movie.imdbRating > 8.0) {
    filteredList.push({
      title: movie.Title,
      rating: movie.imdbRating,
    });
  }
  return filteredList;
});

Thank you to anyone who looked at this and hopefully this can help someone else who may be stuck!

This isn’t how filter works. filter takes a function which returns true or false. And for every value in your array, if that function returns true, then it gets put into a new array.

The callback function should not have any side effects: so for example, I should be able to test what you’ve written there by running your code on something like [{Title: 'Foo', imdbRating: 1.0}, {Title: 'Bar', imdbRating: 9.5}]. I can’t do that because it modifies something outside the function.

watchList.filter((movie) => {
  return movie.imdbRating > 8.0;
});

Hey Dan! Thank you for your reply and for the examples. I ran into some problems after this one with using .filter() the way I did and your answer really helped me. Even though my code worked I can see the problems with it.

Thank you again for your helpful reply! Have an awesome day!

1 Like

You can use forEach() in that way, and also map() is useful


1 Like