somebody could explain why the challenge uses this syntax Array.prototype.myFilter = function(callback)
and how it works?
i dont understand either when it calls the function var new_s = s.myFilter(function(item)
exatly the part s.myFilter
i imagine that its the same answer for both question because i dont understand how this works
its the first time i see something like that, i dont have problems with the algorithm but with the syntaxis that the challenge uses
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
// Add your code above this line
return newArray;
};
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype
So the point of this exercise is essentially to recreate the Array.prototype.filter()
method. The first line you refer to uses that syntax because it’s actually making changes to Array.prototype in the form of adding on an additional method, myFilter. This means all array objects will now inherit access to this method.
So think about what filter does, it takes an array and subjects each item in the array to a logic test based on a function (callback in the above code), pushing each object that passes the test into a new array which is then returned as the output.
So in the above question, we see that newArray has already been initialized inside myFilter, and that it’s going to be returned as the output of myFilter. So what you want to do is decide what code should go in between the comments in order to complete the myFilter function so that it subjects input to the function callback and if callback(input) is true, then it pushes the item to a new array.
For further clarification, since we have added myFilter to Array.prototype the array, s, now inherits that method. So we can invoke that with a callback function as the argument and store the result as new_s:
var new_s = s.myFilter(callback)
where the callback in this case is:
function(item) { return item % 2 === 1};
so the final result is:
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
Hope that helps
EDIT: Just wanted to add that the point of that challenge is just to help you understand the filter method better. As I understand, adding your own methods to Array.prototype can cause issues down the line.