Created
February 22, 2017 22:22
-
-
Save ccnokes/97db422f216012021e812ff4fd40c6b0 to your computer and use it in GitHub Desktop.
Function that sums objects of the same shape
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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