Skip to content

Instantly share code, notes, and snippets.

@r-winkler
Created August 10, 2016 17:40
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 r-winkler/834b35baf60ed4028f97d2444a2fa01c to your computer and use it in GitHub Desktop.
Save r-winkler/834b35baf60ed4028f97d2444a2fa01c to your computer and use it in GitHub Desktop.
var arr = [
{ name: "A", value: 10 },
{ name: "B", value: 20 },
{ name: "C", value: 30 },
{ name: "A", value: 40 },
{ name: "B", value: 50 },
{ name: "C", value: 60 }];
var accumulated = arr.reduce(function(accumulator, element) {
var currentValue = accumulator[element.name];
if(currentValue !== undefined) {
accumulator[element.name] = currentValue + element.value;
}
else {
accumulator[element.name] = element.value;
}
return accumulator;
}, {});
var result = Object.keys(accumulated).map(function(k) {return {name: k, value: accumulated[k]}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment