Skip to content

Instantly share code, notes, and snippets.

@ermauliks
Last active September 22, 2019 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ermauliks/9e4703f91ab59ed141e17d28a2b10f09 to your computer and use it in GitHub Desktop.
Save ermauliks/9e4703f91ab59ed141e17d28a2b10f09 to your computer and use it in GitHub Desktop.
Implementation of Map and Filter Array function in JavaScript
Array.prototype.myMap = function(fn) {
let newArray = [];
this.forEach(item => {
newArray.push(fn(item));
})
return newArray;
}
Array.prototype.myFilter = function(fn) {
let newArray = [];
this.forEach(item => {
if (fn(item))
newArray.push(item);
})
return newArray;
}
let map = [1, 2, 3, 4, 5];
const sqrt = (a) => a * a;
const gt2 = (a) => a > 2;
console.log(map.myMap(sqrt));
console.log(map.myFilter(gt2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment