DEV Community

Randy Rivera
Randy Rivera

Posted on

Functional Programming: Implementing the filter Method on a Prototype

  • 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 a for loop or Array.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;
});
Enter fullscreen mode Exit fullscreen mode
  • 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;
});
Enter fullscreen mode Exit fullscreen mode

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.

Latest comments (0)