How to implement map function

Tags:
Date:

Wednesday 27/07/2022

For implementing arr.map() we will have to create new function on the Array.prototype. Then we will loop over array that the method was called on and finally we will return a new array.

The "this" in our case is the array that will be called with our method "myMap()".

const arr = [1,2,3,4]
Array.prototype.myMap = function(cb) {
    const newArr = []

    for(let i=0; i<this.length; i++) {
        newArr.push(cb(this[i]))
    }
    return newArr
}

Now lets run it

    arr.myMap(x => x*2)

And the result will the same as regular map()

[2,4,6,8]

© 2023 Vadim Alakhverdov