Need a little help thinking

Tell us what’s happening:
in the exercise, we need to access the function first and make every item perform the function. after that, i need to push the new items one-by-one to the newArray.
is my thinking right here?
another problem, which i think is the major one here, is i’m not able to understand how i should “get hold” of the items INSIDE the array. in order for the function to work, i need the item and then the function right?
am i wrong?

  **Your code so far**

// The global variable
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
var newArray = [];
// Only change code below this line
console.log(newArray.push(this.forEach(callback)))
// Only change code above this line
return newArray;
};

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

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.115 Safari/537.36

Challenge: Implement map on a Prototype

Link to the challenge:

Your problem is here. Removing the log to make things clearer:

newArray.push(this.forEach(callback))

You are pushing (once) the return value of the forEach. But forEach doesn’t return anything so you will always end up with an array with one undefined element.

You need to rethink this line. I would want to loop through the values, and push the return value of the element being processed through the callback function.

i need to push the new items one-by-one to the newArray.
is my thinking right here?

Yes, but as mentioned, that’s not what you’re doing.

i’m not able to understand how i should “get hold” of the items INSIDE the array. in order for the function to work, i need the item and then the function right?

Yes. Each element will be passed into the callback function of the forEach. If this is confusing you, maybe do it with a for loop first.

1 Like

thank you very much for your reply. why doesn’t forEach work? i mean, it already has a parameter requirement(which is each item in the array aka this). shouldn’t it return the changed values back?

why doesn’t forEach work?

It can work fine. I changed your code to work and kept the forEach. I merely suggested doing it with a for loop instead in case forEach was confusing you.

shouldn’t it return the changed values back?

No, because all forEach does is, “OK for each element, do whatever the callback says.” forEach isn’t for returning things, it’s for doing things. It is essentially the functional programming equivalent of a for loop. Would you expect a for loop to return something?

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.