Capture multiple values for ES6 array’s map function

I want to perform an operation involving the current and the next array element.

For example, add current element with the next:

let arr = [0,1,2,3,4,5];
let newarr = arr.map((a,b) => a+b); //here, a and b are treated as the same element

expecting it to yield a new array of sums of current and next array element:

[0+1, 1+2, 2+3, 3+4, 4+5]

Is it possible to do that with map? If not, is there any other method that is suitable for manipulating multiple array elements in one operation?

Answer

here, a and b are treated as the same element

No. a is the value and b is the index. They happen to be the same in your particular data set.

Is it possible to do that with map?

Not with map itself. That will give you a new value for each value in the array, but you are starting with 6 values and ending up with 5, so you need an additional transformation.

Obviously you also need to use “the next value” instead of “the current index” too.

const arr = [0,1,2,3,4,5];
const newarr = arr.map((value, index, array) => value + array[index + 1]);
newarr.pop(); // Discard the last value (5 + undefined);
console.log(newarr);

Leave a Reply

Your email address will not be published. Required fields are marked *