I can’t seem to grasp this concept. Can someone explain to me why this returns a function?
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
this.forEach(i => {
if(callback(i)) {newArray.push(i)
}
});
return newArray;
}
// Add your code above this line
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
in a repl.it, it will return “3” because it is evaluating what I have there.
If I do:
Array.prototype.myFilter = function(callback) { }
It returns back a function. repl.it doesn’t list the whole function so it just tells you what it is. It is one of the oddities of command line JS. Don’t worry about it.
You can still use a traditional for loop instead of using a forEach
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
for(var i=0; i<s.length; i++){
if (callback(s[i])) {
newArray.push(s[i]);
}
}
return newArray;
}
// Add your code above this line
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
I was confused by trying to simply push each number in s onto newArray instead of actually filtering each number. After solving this, I think this might help:
You’re trying to return the numbers in s that, when divided by 2, have a remainder of 1 (basically odd numbers). Once you run though each number in s using forEach or a for loop, you need to check IF the number % 2 === 1. If that’s the case, then you can push the number onto newArray.
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
this.forEach(i => {
if (callback(i)){
newArray.push(callback(i));
}
});
console.log(newArray);
// Add your code above this line
return newArray;
};
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
for(let prop in this){
if(callback(this[prop])){
newArray.push(this[prop])
}
}
// Add your code above this line
return newArray;
};
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
// is there anything wrong with this, in this use case?