I wonder if there is a better way of generating a better performing solution for partial sums of an array.
Given an array say x = [ 0, 1, 2, 3, 4, 5 ]
, I generated sub-arrays of the items, and then computed the sum of each array which gives:
[ 0, 1, 3, 6, 10, 15 ]
So the full code is:
x.map((y,i)=>x.filter((t,j)=>j<=i)) .map(ii=>ii.reduce((x,y)=>x+y,0))
I wonder if flat map or some other array method will have a solution that does not require expanding each subarray.
Introduction to the JavaScript Array reduce() methodFirst, declare an array of three numbers 1, 2 and 3. Second, declare the sum variable and set its value to zero. Third, in the for loop, add up the elements of the numbers array to the sum variable. After the loop, the value of the sum variable is 6.
Much, by keeping a running total:
function* partialSums(iterable) { let s = 0; for (const x of iterable) { s += x; yield s; } } const x = [0, 1, 2, 3, 4, 5]; console.log(Array.from(partialSums(x)).join(', '));
Linear time, online. (You can also produce an array directly; expand below.)
const partialSums = arr => { let s = 0; return arr.map(x => s += x); }; const x = [0, 1, 2, 3, 4, 5]; console.log(partialSums(x).join(', '));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With