Implement map using forEach

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

My code using forEach


Another, sillier way:


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:

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 )

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++){

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){
  return newArray;

var new_s = s.myMap(function(item){

The myMap method should be the one pushing the item into an array. Also, you should not be using a global variable (newArray) for this challenge. The built-in map method creates a local array inside the method to add the element’s of the original array which have been modified/returned by the callback function. Your myMap method should do the same.

Do not modify the original challenge code outside of the designated areas.

  // Add your code below this line
   This is where you put your myMap method.  
   Do not modify any existing code outside of this section.  
  // Add your code above this line

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 
 // Add your code above this line

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++){