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

Use the filter method to extract data from an array


Hints

Hint 1

This challange is solved in 2 steps.
First, Array.prototype.filter is used to filter the array so it’s left with elements that have imdbRating > 8.0.
After that, Array.prototype.map can be used to shape the output to the desired format.


Solutions

Solution 1 (Click to Show/Hide)
// Add your code below this line

var filteredList = watchList
  .map(movie => {
    return {
      title: movie.Title,
      rating: movie.imdbRating
    };
  })
  .filter(movie => {
    // return true it will keep the item
    // return false it will reject the item
    return parseFloat(movie.rating) >= 8.0;
  });

Code Explanation

In the beginnner solution we’re mapping over the watchList array to reduce the amount of data we have to work with and only returning the two items we need. Once we’ve reduced the items to what we’re interested in (Title and imdbRating) we’re filtering through and only returning the remaining items that meet the criteria. In this case it’s having an imdbRating of 8.0 or higher.

Solution 2 (Click to Show/Hide)
// Add your code below this line

var filteredList = watchList
  .map(function(e) {
    return { title: e["Title"], rating: e["imdbRating"] };
  })
  .filter(e => e.rating >= 8);

console.log(filteredList);
18 Likes

Hi The only problem is that we need to correct conditions or text. Watch it out here

5 Likes

Hey fellow campers,here is how I did it:

var oldArray = [1,2,3,4,5,6,7,8,9,10];

// Only change code below this line.

var newArray = oldArray.filter(function(val) {
return val < 6;
});

7 Likes

the condition " return val <= 5" isn’t working and it’s weird.

2 Likes

and the condition " return val < 6" also not working…

2 Likes

Hello @garnicha.The instruction says that we use "filter" to create/return a new array with all the values from oldArray which are less than 6.

So, simply put,our new array should not have a number which is 6 or more than 6.Like this:

var oldArray = [1,2,3,4,5,6,7,8,9,10];

// Only change code below this line.

var newArray = oldArray.filter(function(val){
return val < 6;

});

4 Likes