Need help understanding Implement map on a Prototype

I’m having trouble visualizing how the correct solutions for this one work. It would be very helpful to actually see a solution with the test data included for one of the tests.

Could someone please update the solution code below using the data from this test case?

Test Case - [23, 65, 98, 5, 13].myMap(item => item * 2)

Hopefully this makes sense. I don’t need an explanation of how it works. I just need to see what the code looks like using real data. Thanks!

Array.prototype.myMap = function(callback) {
const newArray = ;
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i], i, this));
}
return newArray;
};

Why don’t you just copy the code and test it yourself?

I literally don’t understand how to plug [23, 65, 98, 5, 13].myMap(item => item * 2) into the code. I’ve tried repeatedly but can’t get it to run.

I had ChatGPT write out the code for me. I would have done that before but couldn’t figure out how to explain it until just now.

Could you please confirm that this looks correct?

Array.prototype.myMap = function(callback) {
const newArray = ;

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

return newArray;
};

const originalArray = [23, 65, 98, 5, 13];
const newArray = originalArray.myMap(item => item * 2);
console.log(newArray); // [46, 130, 196, 10, 26]

My main issue was that I didn’t understand the syntax (if that’s the correct word) for calling this kind of function and passing in the callback. If I don’t understand how a function is working I usually just run the code and analyze what comes out and that helps me to understand. Couldn’t do that in this case due to the aforementioned lack of understanding.

I highly recommend anyone who struggles from time to time with understanding how a specific method, function, etc works, grab a ChatGPT account. I find it’s explanations to be very clear.

As an example, below is the chat that I had with ChatGPT regarding my lack of understanding for the function referenced in this forum thread. Note, I do not use ChatGPT to solve challenges in the course (though it could). I only use it to get a better understanding of how things work.

Hopefully it doesn’t take our would be jobs anytime soon :grimacing:

(I’ve blurred as the first image shows the answer to a challenge)

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