Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Created February 22, 2017 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/97db422f216012021e812ff4fd40c6b0 to your computer and use it in GitHub Desktop.
Save ccnokes/97db422f216012021e812ff4fd40c6b0 to your computer and use it in GitHub Desktop.
Function that sums objects of the same shape
// objs[] *must* be the same shape
// returns new object with summation of all properties
function sumObjs(objs) {
const keys = Object.keys(objs[0]);
// initialize return object with 0s
const ret = keys.reduce((aggr, k) => {
aggr[k] = 0;
return aggr;
}, {});
// sum each property
return objs.reduce((aggr, obj) => {
keys.forEach(k => {
aggr[k] += obj[k];
});
return aggr;
}, ret);
}
//e.g. sumObjs([ {a:2}, {a:3} ]) => {a:5}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment