1

I am looking at trying to implement the map function myself.

So far my code looks like this:

Array.prototype.mapz = function (callback) {
    let arr = []
    for (let i = 0; i < array.length; i++) {
       arr.push(callback(array[i]));
    }
    return arr;
};

function double(arg) {
    return arg * 2
};

const x = [1, 2, 3].mapz(double);
console.log(x); // This should be [2, 3, 6];

I am wondering how I can get access to the array I am mapping over in my mapz method?

2
  • btw, you are not mutating the original. Commented Feb 1, 2019 at 11:38
  • correct @NinaScholz updated question Commented Feb 1, 2019 at 12:39

4 Answers 4

2

You could access with this.

Array.prototype.mapz = function (callback) {
    let arr = [];
    for (let i = 0; i < this.length; i++) {
       arr.push(callback(this[i]));
    }
    return arr;
};

function double(arg) {
    return arg * 2;
}

const x = [1, 2, 3].mapz(double);
console.log(x);

Sign up to request clarification or add additional context in comments.

1 Comment

stackoverflow.com/questions/54479758/… - probably a good one for you
1

Use the this keywork to access the array inside your function:

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

const x = [1, 2, 3].mapz(value => value * 2);
console.log(x);

Comments

0

You can simply use this

Array.prototype.mapz = function (callback) {
    let arr = []
    for (let i = 0; i < this.length; i++) {
       arr.push(callback(this[i]));
    }
    return arr;
};

Comments

0

You can use this keyword to access the array

Array.prototype.mapz = function (callback) {
    let arr = []
    for (let i = 0; i < this.length; i++) {
       arr.push(callback(this[i]));
    }
    return arr;
};
function double(arg) {
    return arg * 2
};
const x = [1, 2, 3,5].mapz(double);
console.log(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.