Implement your own map, reduce, filter or any new array method in Javascript | Prototypes

Javascript has many inbuilt methods for Javascript Array. In this blog, we will implement our own map, reduce, filter methods. We will also learn to write any custom method for Javascript Arrays.

Implement your own map, reduce, filter or any new array method in Javascript | Prototypes


All the inbuilt methods are part of Array Prototype and they can can access the array that's calling the function by referring to the current scope. You can read about prototypes and prototype chain if you aren't aware of it.

Let's implement a custom function sum:
var arr = [1,2,3];

arr.sum()

Output: 6
In order to implement this we should understand that this doesn't work as normal function. We have to add sum method to Array Prototype. 

Array.prototype.sum = function(){
var sum = 0;
for(var i=0;i<this.length;i++){
sum =+ this[i];
}
return sum
}

Adding a sum method to Array.prototype gives us access to the current scope, which is nothing but arr.
We can access arr by using "this" as this refers to the current scope on which this method is called.

What we can see here is that we are trying to implement the logic for sum inside the sum method. But in order to create map, reduce, filter, we need to implement a method that can take the modifier from outside in order to make it more generic.

Array.prototype.map = function(callback){
var mapArray = [];
for(var i=0;i<this.length;i++){
mapArray.push(callback(this[i]))
}
return mapArray
}

arr.map((n) => {
return n+1;
})

Output: [2,3,4]


Here we can see that we are taking the modifier from outside in form of callback. Callback is responsible for modifying the data of the original array. We are giving user the flexibility to write its own map.

Similarly with Filter,

Array.prototype.filter = function(callback){
var filterArray = [];
for(var i=0;i<this.length;i++){
if(callback(this[i])){
filterArray.push(this[i])
}
}
return filterArray
}
arr.filter((n) => {
return n == 1;
})

Output: [1]


And Reduce,

Array.prototype.reduce = function(callback,
accumulator){
for(var i=0;i<this.length;i++){
accumulator =+callback(accumulator,
this[i])
}
return accumulator
}
arr.map((n,m) => {
return n+m;
}, 0)

Output: 6

I hope you liked this blog on Implement your own map, reduce, filter or any new array method in Javascript. It's also one of most asked javascript interview question.

Comments

  1. Nice reading, I love your content. This is really a fantastic and informative post. Keep it up and if you are looking for Prototype Development then visit KHolder Development 

    ReplyDelete

Post a Comment