Tell us what’s happening:
I have the function prototype correctly filtering, but I am getting a filter of true or false upon each value, rather than the value itself. Is there a way to guide me along without giving answer away?
Your code so far
// The global variable
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
// Only change code below this line
var newArray = [];
for(let i=0; i < this.length; i++){
newArray.push(callback(this[i]))
}
// Only change code above this line
return newArray;
};
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
console.log(new_s);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.
Challenge: Implement the filter Method on a Prototype
FYI i can get the numbers to print, but only if i alter the bottom code and I don’t believe that’s correct as i’m only supposed to alter the code in between the commented out section
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
// Only change code below this line
var newArray = [];
for(let i=0; i < this.length; i++){
if(this[i] % 2 ===1){
newArray.push(callback(this[i]))
}
}
// Only change code above this line
return newArray;
};
var new_s = s.myFilter(function(item){
return item
});
console.log(new_s);
Hey, very nice exercise!
You get a boolean because of this return value:
return item % 2 === 1;
So, if I get your idea, this should return the item instead, maybe something like this:
return item % 2 === 1 && item;
pd: this will return false sometimes. So you probably should rewrite the conditional, using an if statement, and an empty else, or just the if statement.
the callback return boolean
if that boolean is true you want to keep the number, if it’s false you want to not keep the number
you do not want the boolean in the resulting array
@anon10002461: the challenge is to implement the filter method, your suggestion is off-topic and outside of allowed space to change