Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list of partial sums using forEach

Tags:

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.

like image 922
Team Cafe Avatar asked Mar 20 '19 10:03

Team Cafe


1 Answers

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);
like image 129
Nina Scholz Avatar answered Sep 27 '22 18:09

Nina Scholz