"Implement a Map prototype" with forEach?

So im running into a bit of an issue. I solved this issue (on beta) through:

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  for(var 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;
});

console.log(new_s);

I wanted to try implementing it with forEach (The for loop makes sense for the most part…)

however something like this DOES NOT work:

// the global Array
var s = [23, 65, 98, 5];

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

};

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

console.log(new_s);

Maybe im not understanding how forEach works? can you not manipulate the array itself?

2 Likes