d3 on how to sum values

d3.js, javascript

Solution

Edited to respond to updated question

You can use `d3.nest()` to group objects by a given key (in this case, the country) and then "roll them up" to sum the value across each of the items belonging to a given country. In your case, a one-liner would look something like this:

d3.nest().key(function(d){
    return d.organisation.Country; })
.rollup(function(leaves){
    return d3.sum(leaves, function(d){
        return d.Value;
    });
}).entries(data)
.map(function(d){
    return { Country: d.key, Value: d.values};
});

Here I'm using `d3.sum`, passing in an accessor function to specify that you want to sum the `Value` of each item:

This returns four objects on your example data:

[{"Country":"USA","Value":40000},
 {"Country":"France","Value":82000},
 {"Country":"Germany","Value":67000},
 {"Country":"Holland","Value":100000}]

Javascript converts the strings into numbers for you. Note that you have some typos in your example data that I had to fix, giving the following:

var data = [ { id:0,Department: "Civil",Value : "40000",Title :"Sustainability",ComID : "45", organisation:{ City:"New York",ComID:"45",Country: "USA"}}, { id:1,Department: "Energy",Value : "82000",Title : "Wind Energy",ComID : "62", organisation:{ City:"Paris",ComID:"62",Country: "France"}}, { id:2,Department: "Medical",Value : "67000",Title : "Neuroscience",ComID : "21", organisation:{ City:"Berlin",ComID:"21",Country: "Germany"}}, { id:3,Department: "Computer",Value : "100000",Title : "Security",ComID : "67", organisation:{ City:"Amsterdam",ComID:"67",Country: "Holland"}}]

Problem

I have the data below: ``` [ { id: 0, Department: "Civil", Value: "40000", Title:"Sustainability", ComID: "45", organisation: { City: "New York", ComID: 45, Country: "USA" } }, { id: 1, Department: "Energy", Value: "82000", Title: "Wind Energy", ComID: "62", organisation: { City: "Paris" , ComID: 62, Country: "France" } }, { id: 2, Department: "Medical", Value: "67000", Title: "Neuroscience", ComID: "21", organisation: { City: "Berlin", ComID: 21, Country: "Germany" } }, { id: 3, Department: "Computer", Value: "100000", Title: "Security", ComID: "67", organisation: { City: "Amsterdam", ComID: 67, Country: "Holland" } } ] ``` the data is an array of about 100 objects like the ones above. In the data I have organizations of the same country. I want to sum the Value attribute of each Country and put it in a new table. For example I would like to create: ``` [ { Name: "each Country", Value: "the summed value" } ] ```

Original source