Implement map using forEach

Hi.
So I did this challenge just fine. But how do I implement it using forEach?

My code using forEach

newArray.push(this.forEach(callback));

Another, sillier way:

this.forEach(newArray.push(callback));

I’d like to know why this doesn’t work and how do I make it work using forEach.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype

My understanding is that forEach takes a function and returns undefined (nothing). So that is why you are struggling with your implementation. ( my ref is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach )

Instead when you call this.forEach give it a new function that combines the callback with the push into it. Hope this helps.

Assuming callback is the transformer function passed to your map(), why are you passing callback to your newArray?
The final output of newArray will only contain callback function as many as this.length. It is not probably what map() should do.

This is what I completed the challenge with

for(let i=0; i<this.length; i++){
  newArray.push(callback(this[i]));
}

Now I wanna know how can I do it using forEach?

arr.forEach(elem => {
     // do somethinng with elem.
})

You figure it out from here.

I was able to work this out.
It works but am not sure if it’s the right way to do it.

// the global Array
var s = [23, 65, 98, 5];
var newArray = [];
Array.prototype.myMap = function(callback){
  this.forEach(callback);
  return newArray;
};

var new_s = s.myMap(function(item){
  newArray.push(item*2);
});
console.log(new_s);

Hi, if you want to see my solution, here it is. Just keep in mind that you may want to try a bit more to solve this (just remember that forEach takes a function and gives back nothing…)

// Add your code below this line 
this.forEach(function(item){
    newArray.push(callback(item));
});
 // Add your code above this line
2 Likes

Thank You.
Helped a lot.

Not that it keeps you from passing the challenge but if you want to fully implement a replacement for .map() you should pass all optional parameters to your callback as well.

callback( currentElement, currentIndex, theArray);

If your callback does not require these optional parameters they will simply go unused.

this works too in case we want to use for loop
for(let i = 0; i < this.length; i++){
newArray.push(callback(this[i]))
}