Skip to content

Instantly share code, notes, and snippets.

@gunar
Last active April 29, 2018 17:13
Show Gist options
  • Save gunar/0d148814e740c1dd6b8f to your computer and use it in GitHub Desktop.
Save gunar/0d148814e740c1dd6b8f to your computer and use it in GitHub Desktop.
Function to sum an object values using recursion
// This is super slow though: http://jsperf.com/summing-objects/2
var sumObj = function (object) {
if (Object.keys(object).length) {
var firstKey = Object.keys(object)[0];
var clone = Object.assign({}, object);
delete clone[firstKey];
return parseInt(object[firstKey]) + sumObj(clone);
}
return 0;
};
@gunar
Copy link
Author

gunar commented Mar 5, 2016

Looks even neater with ES6:

const sumObj = obj => Object.keys(obj).reduce((sum, next) => sum + object[next], 0)

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