# Implement map on a Prototype

## Solutions

Solution 1 (Click to Show/Hide)
``````// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
var newArray = [];
// Add your code below this line
this.forEach(a => newArray.push(callback(a)));
// Add your code above this line
return newArray;
};

var new_s = s.myMap(function(item) {
return item * 2;
});
``````

#### Code Explanation

• Solve this challenge using `this` and the forEach method

• The `this` keyword gives us access to the object we are calling myMap on.

• From there we can use the forEach method to add elements to already declared empty array as we modify each element with the given callback method.

Solution 2 (Click to Show/Hide)
``````// The global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
var newArray = [];

// Add your code below this line
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i]));
}
// Add your code above this line

return newArray;
};

var new_s = s.myMap(function(item) {
return item * 2;
});
``````

#### Code Explanation

• Solve this challenge using a â€śforâ€ť loop and `this`

• The use of a â€śforâ€ť loop allows us to apply the callback function to every item in the Global array and then push the modified items to the empty new array that is returned in the end.

Solution 3 (Click to Show/Hide)
``````// The global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback, arr = [], i = 0) {
return i < this.length
? this.myMap(callback, arr.concat(callback(this[i])), i + 1)
: arr;
};

var new_s = s.myMap(function(item) {
return item * 2;
});
``````

#### Code Explanation

• Solve this challenge using recursion