Blank
Blank

Reputation: 96

How do I implement the map() function using a for loop?

I'm a beginner and I'm still trying to understand some concepts. I basically have to rewrite the behavior of the map() function using a for loop.

Being an exercise from a course, part of the code has already been provided me:

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

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line



  // Add your code above this line
  return newArray;
};

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

I thought this way: map is a function with a function as parameter, so the "callback" in the parentheses has to be a function and as its goal is to execute the function to every element of an array I'll need indeed a for loop and to pass an array as parameter.

so this is what I wrote:

Array.prototype.myMap = function(callback){
    var newArray = [];
    // Add your code below this line
        for(let i = 0; i < this.length; i++){
           newArray.push(this[i].callback);
        } 
    // Add your code above this line
    return newArray;
  }

I basically put a for cycle where "this" is supposed to be the array which uses the map() function but I'm not sure it's logically correct. Then I pushed into the array the result given by using the "callback" function to the actual element in the loop.

Unfortunately the result is an array of empty strings.

This is what the console shows me:

,,,

Thank you in advance, hope you can help to figure it out

Upvotes: 1

Views: 1973

Answers (2)

Davi
Davi

Reputation: 4147

You're almost there:

Array.prototype.myMap = function(callback){
    var newArray = [];
    // Add your code below this line
        for(let i = 0; i < this.length; i++){
           newArray.push(callback(this[i]));
        } 
    // Add your code above this line
    return newArray;
  }
  
  
console.log([1, 2, 3].myMap(function (num) { return num + 2; }));

The purpose of map is to project a function over a value. In the case of Array, it "maps" the function over each value inside the array.

Upvotes: 1

Fullstack Guy
Fullstack Guy

Reputation: 16908

You need to call the callback with the current value of this[i].

var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
    var newArray = [];
    // Add your code below this line
        for(let i = 0; i < this.length; i++){
           newArray.push(callback(this[i])); //pass the value of this[i] to the callback function.
        } 
    // Add your code above this line
    return newArray;
  }
var new_s = s.myMap(function(item){
  return item * 2;
});
console.log(new_s);

Upvotes: 3

Related Questions