How to make a list of partial sums using forEach

arrays, ecmascript-6, foreach, javascript

Solution

You could save a sum and add the values.

var array = [[1, 1, 1, -1], [1, -1, -1], [1, 1]],
    result = array.map(a => a.map((s => v => s += v)(0)));

console.log(result);

By using `forEach`, you need to take the object reference and the previous value or zero.

var array = [[1, 1, 1, -1], [1, -1, -1], [1, 1]];

array.forEach(a => a.forEach((v, i, a) => a[i] = (a[i - 1] || 0) + v));

console.log(array);

Problem

I have an array of arrays which looks like this: ``` changes = [ [1, 1, 1, -1], [1, -1, -1], [1, 1] ]; ``` I want to get the next value in the array by adding the last value ``` values = [ [1, 2, 3, 2], [1, 0, -1], [1, 2] ]; ``` so far I have tried to use a forEach: ``` changes.forEach(change => { let i = changes.indexOf(change); let newValue = change[i] + change[i + 1] }); ``` I think I am on the right lines but I cannot get this approach to work, or maybe there is a better way to do it.

Original source

Related problems