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 challenge is solved in 2 steps.

Array.prototype.filter() is used to filter the array so it’s left with elements that have imdbRating > 8.0.

Array.prototype.map() can be used to shape the output to the desired format.


Solutions

Solution 1 (Click to Show/Hide)
const filteredList = watchList
  .filter(movie => {
    // return true it will keep the item
    // return false it will reject the item
    return parseFloat(movie.imdbRating) >= 8.0;
  })
  .map(movie => {
    return {
      title: movie.Title,
      rating: movie.imdbRating
    };
  });

Code Explanation

First we filter through and only return the objects that meet the criteria. In this case the criteria is having an imdbRating of 8.0 or higher.
Then we map the objects to the desired format.

Solution 2 (Click to Show/Hide)
const filteredList = watchList
  .filter(movie => movie.imdbRating >= 8.0)
  .map(movie => ({ title: movie["Title"], rating: movie["imdbRating"] }));
// Only change code above this line
console.log(filteredList);
Solution 3 (Click to Show/Hide)
// Only change code below this line
const filteredList = watchList
  .filter(({ imdbRating }) => imdbRating >= 8.0)
  .map(({ Title: title, imdbRating: rating }) => ({ title, rating }));
// Only change code above this line

console.log(filteredList);

Relevant Links

75 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;
});

9 Likes

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

3 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;

});

5 Likes