If I have an object containing 20 keys, and over 3000 entries, is there a way using d3 to SUM the entire object?
For example if I have:
Country: Germany, val2007:9.3, val2008:8.6
Country: Germany,val2007:3.4, val2008:1.0
Country: Austria, val2007:23.0, val2008:9.2
Country: Austria, val2007:1.2, val2007:3.2
Can I produce an array as the following?
Country: Germany,val2007:12.7, val2008:9.6
Country: Austria, val2007:24.2, val2008:12.4
Bearing in mind that I won’t know the key names all the time and the ‘val’ fields could be anything from val2007 and val2008 to val1997 -> val2017
D3 doesn’t provide a simple way to do this, but it offers several tools that are useful. The first is
d3.nest(docs), which can group rows on specific keys. After that, you need to figure out how to sum the rows for, say, Germany yourself – here I useArray#reduce, which I think works well for this sort of problem:You can see the working fiddle here: http://jsfiddle.net/nrabinowitz/MB3yz/