Implement map on a Prototype for in question

Implement map on a Prototype for in question
0

#1

Tell us what’s happening:
Hey guys. I was working on this lesson and was able to succeed using a normal for loop.
But I initially tried using a for each loop, and was unsuccessful. when I used a console.log(x) in the for each loop I noticed that x iterated through each element in the array and myMap.
Why is this happening? myMap isn’t an element in the array so I’m confused where it came from or how to do this in a for each way.

Your code so far


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

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  for (var x in s) {
    newArray.push(s[x]*2);
  }  
  // Add your 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 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

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


#2

myMap isn’t an element in the array so I’m confused where it came from or how to do this in a for each way.

It’s true^^ myMap is not an element, is a custom method just defined by you! Think about .map(), .filter(), .split(), .slice(), and so on…now the arrays have the method myMap too :grin:
That’s the reason why your code is not a solution even if it passes all the test: your code should behave the same of the map method but if I use yours I will always be given back the s items multiplied 2 :frowning:

Think about the this object, which you can use to refer to the general array against you can use your method
After that think about what map do: take each of the array elements, pass them as argument to the callback and return a new array composed by the result of these operation^^

Below i blurred the forEach solution but i suggest you to give yourself a chance to solve it!

this.forEach(el => newArray.push(callback(el)));

#3

I felt like some of the answers i saw were a bit confusing. So I wrote in the comments of my solution what each part was doing.

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

Array.prototype.myMap = function(callback){
  //callback is a funtion which returns item *2

  var newArray = [];
  // Add your code below this line
  
  this.forEach(el=> // for each element in 'this'
  //this being the array myMap is being called on.
     newArray.push(callback(el))//multiply the element
     //by 2 with callback, and then push that into the newarray.
     );
  // Add your code above this line
  return newArray;

};

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