This is an example of what I need to do:
var myarray = [5, 10, 3, 2];
var result1 = myarray[0];
var result2 = myarray[1] + myarray[0];
var result3 = myarray
My initial ES6 thought was similar to a few above answers by Taeho and others.
const cumulativeSum = ([head, ...tail]) =>
tail.reduce((acc, x, index) => {
acc.push(acc[index] + x);
return acc
}, [head])
console.log(cumulativeSum([-1,2,3])
The solution performs:
n lookups, n - 1 sums and 0 conditional evaluations
Most of what I saw above appeared to use:
n lookups, 2n sums, and n conditional evaluations:
You could do this with ie6 safe js as well. This is possibly more efficient since you don't have to create the tail spread array.
function cumulativeSum(a) {
var result = [a[0]];
var last = a[0];
for (i = 1; i < a.length; i++) {
last = last + a[i];
result.push(last)
}
return result;
}
console.log(cumulativeSum([-1,2,3]))