How to Write Your Own Reduce, Filter and Map Methods in JavaScript
Writing your own Reduce, Filter and Map methods in JavaScript
This article is inspired from one of the JavaScript Mock interviews on YouTube.
The question was:
Write a function print()
such that [1, 2].print()
outputs 1,2 when print(
) is invoked on the array.
This question made me inquisitive and I researched similar questions of the same type.
That’s what I am going to share in this article.
Before beginning, first let’s get some basics out of the way.
The basic information we need is:
map()
, filter()
and reduce()
methods are invoked on arrays and written in Array class in JavaScript.
Let’s keep this in the back of our mind before proceeding.
Okay. One method at a time.
Writing your own map()
method
Let’s have a look at the map()
method.
var a=[5,2,6,8];
var r = a.map(item => item*2); // map() is invoked here
console.log(r);
The output is: Array [10, 4, 12, 16]
What does map()
method do exactly?
map()
method preforms an operation and returns the output in an array.
Alright.
Can you show me the syntax of the method?
Sure.
Below is the syntax of map()
method from MDN:
let new_array = arr.map(function callback( currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])
The syntax says: there is a callback
function passed to the map()
method. The parameters to perform the operation are passed in the callback
function.
Okay.
How do we start with our own map()
method?
With declaration of our own myMap()
method.
Array.prototype.myMap = function(callback){} // declaring map()method.
We have named our method myMap()
so that it doesn’t conflict with the map()
existing method.
This callback
passed in the function indicates that we have to call the callback
function some time in the future. It can be any name of your choice but for ease of understanding we will go with callback
.
What are the steps to begin writing our own map()
method?
The four simple steps are:
- Declare an array that stores the results.
- Run a loop from 1 to n. ( n is the length of the array).
- Push the results in the array declared in step(1).
- Return the result array.
Let’s try to implementing it now.
Array.prototype.myMap=function(callback){
var arr = []; // step 1
for(let i=0; i<this.length; i++) // step 2
{
arr.push(callback(this[i])); // step 3
}
return arr; // step 4
};
What is this
?
this
is a keyword in JavaScript. this
gives us the array that invoked the myMap()
method.
Let’s see our myMap()
method with the output.
We have successfully created and invoked our own map()
method. myMap()
works just the same.
What’s next?
Writing your own filter()
method
After writing our own map()
method let’s try our own filter()
method.
What does filter()
method do?
Let’s have a look at the filter()
method.
var a=[5,21,61,8,1];
var result = a.filter(i => i>20);
console.log(result);
The output is: Array [21, 16]
What does filter()
method do?
filter()
method passes a test and returns the results in an array.
And what is the syntax for the filter()
method?
Here is the syntax from MDN :
let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])
Just like the myMap()
method. A callback
is passed to the method and an array is returned.
All we have done here is performing an operation and the filter()
method returns an array containing all the elements that pass the test.
The skeleton of the method is:
Array.prototype.myFilter=function(callback){}
We will write the function in four steps:
- Declare an array that stores the results.
- Perform the operation.
- Store the result in the array that saves the result.
- Return the result array.
Now, let’s implement all the steps
Array.prototype.myFilter = function(callback){
var arr = []; // step 1
for(let i=0; i<this.length; i++)
{
if(callback(this[i]) == true) // step 2
{
arr.push(this[i]); // step 3
}
}
return arr; // step 4
}
How we will invoke this method and what would be the output?
Here it is
this
gives us the array and callback
is the function passed to be invoked later.
We check using if
condition whether the condition is met. We collect only those elements in the array that pass the test.
Writing your own reduce() method
Let’s have a look at the reduce()
method:
var arr=[5,21,61,8,1];
var result = arr.reduce((acc, item) => acc+item);
console.log(result);
What does reduce()
method actually do?
reduce()
method adds all the element in the array and returns the sum.
Let’s have a look at the syntax from MDN:
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
The reduce() method has two parameters an accumulator and value. The accumulator sums up and accumulates results of all the items in the array.
How do we start with our own reduce()
method?
With declaring our function:
Array.prototype.myReduce = function(callback)(){}
Then following these four simple steps:
- Declare an accumulator
- Run a for loop from 1 to n
- Accumulate the sum all the elements in the array in the accumulator in step(1)
- Return the accumulator
Let’s see how we go about it.
Array.prototype.myReduce = function(callback){ var a =0; // Step 1 for(let i=0; i<this.length; i++) // Step 2
{
callback(a = a+this[i]) // Step 3 }
return a; // Step 4}
This is what we get when we follow all the steps. var a
is the accumulator. We call the callback
function when we run the for
loop. All the elements of the array are available in this
keyword.
Now, let us write the code see the execution as well
This myReduce()
works just like the original reduce()
method. And gives us the correct output.
I have touched the basics and written this article to the best of my understanding. Do let me know in case of any errors and omissions. Thanks for reading.