Javascript Problems – Create my own Array.prototype.map() method – myMap()

In this exercise, I will create my own map method – myMap(). According to MDN Developers Network, “The map() method creates a new array with the results of calling a provided function on every element in the calling array.”

I have used the same sample data and functions as I did for the myForEach problem.  While myForEach() processes each item in an array separately, myMap() modifies every element in the array and then returns the array.

On line 2, I add a new myMap() method to the array object, which takes a function for an argument.  I then loop through each item in the array.  On line 4, I update the array item as modified by the function.

On line 22, I apply the addOne function to the numbers array [1,2,3] using the myMap method.  It adds 1 to each number, and returns [2,3,4].  On line 22, I apply the addOne function once again to the letters array [“a”,”b”,”c”], returning [“a1”, “b1”, “c1”].  Finally, on line 24, I apply the addTax function to the sales array [100,225, 15], grossing up the sales price 10% and returning [ ‘110.00’, ‘247.50’, ‘16.50’ ].

// create my own map method
Array.prototype.myMap = function(func) {
    for(let i=0; i<this.length; i++) {
        this[i]=func(this[i]);
    }
    return this;
};

function addOne(item) {
    return item+1;
}

function addTax(item) {
    // add 10% sales tax
    return (item*1.1).toFixed(2);
}

const numbers = [1,2,3];
const letters = ["a", "b", "c"];
const sales = [100,225, 15];

console.log(numbers.myMap(addOne)); // [ 2, 3, 4 ]
console.log(letters.myMap(addOne)); // [ 'a1', 'b1', 'c1' ]
console.log(sales.myMap(addTax)); // [ '110.00', '247.50', '16.50' ]

 

Leave a Reply

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