Use the filter Method ,to Extract Data from an Array

Hi campers, in this challenge I don’t know why my filter is not returning the result I should arrive to it at the end .I need some signs.

// Add your code below this line

var filteredList=watchList.filter(function(item){
 let num=Number(item.imdbRating);
    if(num>= 8){
        return {title:item.Title,rating:item.imdbRating};
    };


});

    

// Add your code above this line

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array/

The callback you need to pass to filter must be a boolean test, I mean, must return a boolean. And filters the items by testing if the result is true or false.

It might be instructive to see a fictitious implementation of filter and how it works

Suppose we defined array.filter as follows:

array.prototype.filter = function(f) {
    var newArr = [];
    for(let i=0; i<this.length; i++) {
        if(f(this[i]) {
             newArr.push(this[i])
        }
    }
    return newArr;
}

as you can see from this, filter uses the function its passed in simply to decide whether or not include the element in the returned array and does not transform the element in any way

Transforming the newly returned array is then your responsibility after the filter, perhaps by using a map or a forEach or however else you choose

(use a map though)

2 Likes

thank you guys ,I didn’t read the instructions very well ,because the want to use a combination between filter and map here is the solution I made:

var filteredList=watchList.filter(function(item){

let num=Number(item.imdbRating);
    if(num>=8){
        return item;
    }

}).map(function(item){
    return {title:item.Title,rating:item.imdbRating};
    
});

It’s still off by a little bit and luck has made it work, but for other problems it will fail

Filter’s function argument is meant to return something truthy (like a Boolean) if it’s meant to keep the value

Change your filter function to be return num >= 8; for the more conventional approach

I couldn’t figure that out , I know that in the filter method the argument that pass the condition will be retuned in a new array , could you please write your workaround.

Yes, the item that passes the condition

return true; is not the same as return item; in general, what if you want to keep the value 0 in the array?

if(item) would then be if(0) which would be false

Here is how I did it:

var filteredList = watchList
                    .filter(item => parseInt(item.imdbRating) >= 8.0)
                    .map(item => {
                      return {title: item.Title, rating: item.imdbRating};
                    });
5 Likes