I am trying to create a custom reduce function for a dataset attribute group that would sum a number of unique values for another attribute.
For example, my dataset looks like a list of actions on projects by team members:
{ project:"Website Hosting", teamMember:"Sam", action:"email" }, { project:"Website Hosting", teamMember:"Sam", action:"phoneCall" }, { project:"Budjet", teamMember:"Joe", action:"email" }, { project:"Website Design", teamMember:"Joe", action:"design" }, { project:"Budget", teamMember:"Sam", action:"email" } So, team members work on a variable number of projects by performing one action per line. I have a dimension by team member, and would like to reduce it by the number of projects (uniques).
I tried the below (storing project in a uniques array) without success (sorry, this might hurt your eyes):
var teamMemberDimension = dataset.dimension(function(d) { return d.teamMember; }); var teamMemberDimensionGroup = teamMemberDimension.group().reduce( // add function(p,v) { if( p.projects.indexOf(v.project) == -1 ) { p.projects.push(v.project); p.projectsCount += 1; } return p; }, // remove function(p,v) { if( p.projects.indexOf(v.projects) != -1 ) { p.projects.splice(p.projects.indexOf(v.projects), 1); p.projectsCount -= 1; } return p; }, // init function(p,v) { return { projects:[], projectsCount:0 } } ); Thanks a lot!
Edit after DJ Martin's answer ::
So, to be clearer, I would like to get the numbers I am after here would be:
----------- Sam : 2 (projects he is workin on, no matter the number of actions) Joe : 2 (projects he is workin on, no matter the number of actions) ----------- The answer provided by DJ Martin gets me there. But rather than hard coding a table, I would like to find a way to use these numbers for my DC.JS bar chart. When I was only using the number of actions (so just a reduceCount() ), I did it like below:
teamMemberChart.width(270) .height(220) .margins({top: 5, left: 10, right: 10, bottom: 20}) .dimension(teamMemberDimension) .group(teamMemberDimensionGroup) .colors(d3.scale.category20()) .elasticX(true) .xAxis().ticks(4); I guess there might be something to change in the group().