Reputation: 3620
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
?
Upvotes: 1
Views: 627
Reputation: 371039
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);
Upvotes: 2