Javascript Concepts

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.reduce((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.

Read my interview experience on Walmart, Amazon, Flipkart, MS, Paytm, MMT, OYO, Intuit, etc.
Links:

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to receive helpful content for your next Front End Interview. No Junk. No Spam.

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

FE / JS will use the information you provide on this form to be in touch with you and to provide updates and marketing.