0

I am implementing the map function. To access the array I am mapping over I am using this based on a question I had earlier. Now I am wondering how to access different arguments passed to the callback. So in the official map method you can pass the index. I am trying to do this, but unsure how to access this in my custom method.

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

let x = [1, 12, 3].mapz((item, index) => {
  return item * 2;
})
console.log(x);

2
  • where do you use index? Commented Feb 1, 2019 at 12:43
  • When you want to get the index in the parameter, you must pass it as an argument! Commented Feb 1, 2019 at 12:47

2 Answers 2

3

You need to hand over the index as second parameter for the callback

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

let x = [1, 12, 3].mapz((item, index) => {
  console.log(index, item);
  return item * 2;
})
console.log(x);

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

1 Comment

thanks again, all makes sense. Just need it spelled out to me at the start :-D
1

You just need to add another argument to your callback function which is your index.

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

let x = [1, 12, 3].mapz((item, index) => {
console.log(index);
  return item * 2;
})
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.