Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save afaqahmedkhan/a5ac418d80b224e80658797e226503bd to your computer and use it in GitHub Desktop.
Save afaqahmedkhan/a5ac418d80b224e80658797e226503bd to your computer and use it in GitHub Desktop.
Functional Programming: Implement the filter Method on a Prototype
It would teach us a lot about the filter method if we try to implement a version of it that behaves exactly like Array.prototype.filter(). It can use either a for loop or Array.prototype.forEach().
Note: A pure function is allowed to alter local variables defined within its scope, although, it's preferable to avoid that as well.
Write your own Array.prototype.myFilter(), which should behave exactly like Array.prototype.filter(). You may use a for loop or the Array.prototype.forEach() method.
// the global Array
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])){
newArray.push(this[i]);
}
}
return newArray;
};
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
@Rupesh-Darimisetti
Copy link

Much cleaner code => Functional Programming: Implement the filter Method on a Prototype

// The global variable
const s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback) {
  // Only change code below this line
  const newArray = [];
  s.forEach((num)=>{if(callback(num))newArray.push(num)})
  // Only change code above this line
  return newArray;
};

const new_s = s.myFilter(function(item) {
  return item % 2 === 1;
});
console.log(new_s);

@VladWide
Copy link

Array.prototype.myFilter = function(callback) {
const newArray = [];
// Only change code below this line
for(let i = 0; i < this.length; i++){
if(callback(this[i], i , this)){
newArray.push(this[i])
}
}
// Only change code above this line
return newArray;
};

[23, 65, 98, 5, 13].myFilter(item => item % 2) should equal [23, 65, 5, 13].

["naomi", "quincy", "camperbot"].myFilter(element => element === "naomi") should return ["naomi"].

[1, 1, 2, 5, 2].myFilter((element, index, array) => array.indexOf(element) === index) should return [1, 2, 5].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment