freeCodeCamp Challenge Guide: Implement map on a Prototype

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.

Relevant Links

this. JavaScript MDN

this. Javascript W3Schools
for loop MDN
Array.prototype MDN

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

Relevant Links

MDN: this keyword

Gentle Explanation of “this” in JavaScript

MDN: Details of the object model

MDN: Inheritance and the prototype chain

24 Likes