Implement map on a Prototype
Solutions
Solution 1 (Click to Show/Hide)
Array.prototype.myMap = function(callback) {
const newArray = [];
// Only change code below this line
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i], i, this));
}
// Only change code above this line
return newArray;
};
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.
Relevant Links
this. JavaScript MDN
this. Javascript W3Schools
for loop MDN
Array.prototype MDN
Solution 2 (Click to Show/Hide)
Array.prototype.myMap = function (callback) {
const newArray = [];
// Only change code below this line
this.forEach((element, index, originalArr) =>
newArray.push(callback(element, index, originalArr))
);
// Only change code above this line
return newArray;
};
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.
Relevant Links
MDN: this
keyword
Gentle Explanation of “this” in JavaScript