Continuing forward. You might learn a lot about the
filter
method if you implement your own version of it as well. It is recommended you use afor
loop orArray.prototype.forEach()
.Ex:
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
// Only change code below this line
var newArray = [];
// Only change code above this line
return newArray;
};
var new_s = s.myFilter(function(item) {
return item % 2 === 1;
});
- Answer:
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
var newArray = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i]) === true) {
newArray.push(this[i])
}
}
return newArray;
};
var new_s = s.myFilter(function(item) {
return item % 2 === 1;
});
new_s
equals [23, 65, 5]Helpful Links:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
Larson, Quincy, editor. “Implement the filter Method on a Prototype.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.
Top comments (0)