Implementing our own Array.map() method in javascript

Dhilip Kumar
Mar 27 · 3 min read
src: google

(For those who are restricted by Medium paywall, I have Shared the story here in Dev community)

If you know how `Array.map()` works in javascript, you can jump to IMPLEMENTATION.

What is Array.map in javascript?

A map is a built-in function of Arrays in javascript which helps us iterate over each individual element of the array and returns a brand new array.

First, let us understand how map behaves,

For Example:

The output of the above snippet will be:

So, we can conclude that for each value of the array the function gets executed. And the function has access to 3 arguments:
* The current element that is processed
* Current element’s index
* Entire Array

We are returning `val*2`on every iteration and that gets stored in`mapResult`.So, mapResult has [2,4,6] in it and this won't modify the original array`sample`.

Thus, whatever that is returned by map during each iteration, will get stored inside a brand new array and the original array remains untouched.

Note: If nothing is returned from the function then,`undefined` gets stored in the output array. And this array’s length will be same as that of the array on which map is done.

If we did not return anything in our previous example then,

`map` will always return an array. So we don’t have to write an explicit return from an Array.map() function which is why we use map most of the times to iterate through lists in React.

IMPLEMENTATION:

Let us create our own map method[mymap]:

Step 1:
* We will create a new method[mymap] which allows us to use`Array.mymap()`
* In order to use Array.mymap() we have to have`mymap()`’s definition in Array.prototype.

Now we will be able to run`[1,2,3].mymap();` which will return`undefined`.

Step 2:
* `map` is called with function as an argument inside it. (eg:`[1,2].map(function(val, index, arr){})`). So, our`mymap` function should accept a function as an argument.
* The function in the argument should be called for each value in the array with 3 arguments:
- The current element
- Current element’s index
- Entire Array
* `this` refers to the array on which`mymap` is done. `this` is the array itself.

Step 3:
Finally, we output the result to a new array and return them.

Output:

That's it :) we have implemented our own map method.

Feel Free to Clap :)

Next step: Try using a similar approach and create a custom map for objects.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade