Skip to content

Instantly share code, notes, and snippets.

@omarish
Created December 16, 2010 23:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omarish/744238 to your computer and use it in GitHub Desktop.
Save omarish/744238 to your computer and use it in GitHub Desktop.
simple cumulative sum in javascript.
cumsum = [];
j = [0,1,2,3,4];
for(var a=0;a<j.length;a++) {
if(a==0) cumsum[a] = j[0];
else cumsum[a] = cumsum[a-1] + j[a];
}
Copy link

ghost commented Jan 31, 2015

With no branching:

var a  = [1,2,3,4,5];
for (var cumsum = [a[0]], i = 0, l = a.length-1; i<l; i++) 
    cumsum[i+1] = cumsum[i] + a[i+1]; 

@Yatoom
Copy link

Yatoom commented Mar 20, 2018

@ghost's method does not work if you want to use let instead of var, because the let-variable gets discarded after the for-loop. Here's my alternative:

function cumSum(a) {
    let result = [a[0]];

    for(let i = 1; i < a.length; i++) {
      result[i] = result[i - 1] + a[i];
    }

    return result;
};

@keithpjolley
Copy link

keithpjolley commented Feb 23, 2019

How about:

let y=0;
let b=[1,2,3,4,5];
cumsum = b.map(d=>y+=d);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment