Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to do partial sums of array items in JavaScript?

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.

like image 260
Patrick Francis Omogbeme Avatar asked Jun 10 '19 00:06

Patrick Francis Omogbeme


People also ask

How do you sum using reduce in JavaScript?

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.


1 Answers

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(', '));
like image 118
Ry- Avatar answered Oct 11 '22 12:10

Ry-