1

Is it possible to go one iteration step backwards in JavaScript's Array.prototype.map or Array.prototype.forEach? i.e. if the current iteration index is, for instance, 2, can we go back to index 1? Keeping in mind that we can achieve this with a normal for-loop by decrementing i, is there a way to do this with map?

1

1 Answer 1

2

You can access the previous element in .map by using the third parameter provided to the callback:

const input = [1, 2, 3];

const output = input.map((num, i, arr) => {
  console.log('last num was ' + arr[i - 1] + ', current num is ' + num);
  return num + 1;
});

But there's no way to assign to the previous element in the new mapped array, since the previous iteration's .map callback has already run and had a value returned.

One method that might accomplish what you're looking for is, instead of looking from the next element backwards, look from the current element forwards, and return the new mapped value based on that:

const input = [1, 2, 3];

const output = input.map((num, i, arr) => {
  console.log('next num is ' + arr[i + 1] + ', current num is ' + num);
  return num + (arr[i + 1] || 0);
});
console.log(output);

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

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.