To gain access to the element preceding it in the context of the .map
method, you can utilize the third argument provided in the callback function:
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;
});
However, it is not possible to directly modify or update the previous element within the newly mapped array since each iteration of the .map
callback has already processed and returned a value for that specific index.
An alternative approach to achieve this functionality is by considering the elements following the current one rather than those preceding it, and use that information to determine the new mapped value:
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);