Reputation: 65
I'm struggling with summing an array. I don't have any error so I am not sure how to make it work.
my data passed to the function look like this:
{Region:'' ,freq:{yesVote:0, noVote:0}}
I try to sum it like this:
// compute pie slice angles
var pie = d3.pie().sort(null).value(function (d) {
var yesTotal;
var noTotal;
console.log(d);
yesTotal = d3.sum(d, function(v){
console.log(v.freq);
return v.freq.yesVote;
});
noTotal = d3.sum(d, function(v){
return v.freq.noVote;
});
console.log(yesTotal);
console.log(noTotal);
return [yesTotal,noTotal];
});
Sum function returns 0 and log function inside sum functions doesn't appear in the console (first log print data properly) so I assume there is something wrong with data passed to the sum function. Can you please explain me where I do mistake?
EDIT
printed data:
Upvotes: 1
Views: 2172
Reputation: 890
If this is what console.log(d)
is producing:
{Region:'' ,freq:{yesVote:0, noVote:0}}
then yes, you're not passing the correct data. You're only passing an object with a single value set. d3.sum()
should operate on the full array of data. Example:
var data = [
{Region: 'A' ,freq: {yesVote:1, noVote:10}},
{Region: 'B' ,freq: {yesVote:2, noVote:11}},
{Region: 'C' ,freq: {yesVote:3, noVote:12}}
];
yesTotal = d3.sum(data, function(d) {
return d.freq.yesVote;
});
noTotal = d3.sum(data, function(d) {
return d.freq.noVote;
});
console.log(yesTotal)
6
console.log(noTotal)
33
Try moving the sum out of the pie chart value function, because inside, d
is just a single row from your entire data set.
Upvotes: 5