Recreate the map() function

So I need to recreate the map() function.
I cant figure out how to access the array that the function is called on. It seems like the function I need to write has now arguments.
How can I access the array?


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

Array.prototype.myMap = function(callback){
var newArray = [];
// Only change code below this line
let args=Array.from(arguments);
console.log(args[0]);
// 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 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0.

Challenge: Implement map on a Prototype

Link to the challenge:

Hello!

Whenever you add functions to an object’s prototype, you can access the actual object with the key word this:

// Let's create a custom findBy function for the array object
// which creates a new array with the values where the callback returns true:
Array.prototype.findBy = function(callback) {
  const copy = [];
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      copy.push(this[i]);
    }
  }
  return copy;
};

const test = [ 1, 'x', 2, 'y' ];
const foundItems = test.findBy(function(item, index, array) {
  return item === 'x' || item === 2;
});
console.log(foundItems);
// Should output:
// [ 'x', 2 ]

I hope it serves as an example :slight_smile:,

Happy coding!

Thanks! Forgot about this

1 Like