I'm trying to display the number of characters from each race in LOTR from a JSON file, the problem is that the data counts each instance of a character, as they are mentioned multiple times in the JSON thus inflating my data too much larger than anticipated results. For example:
{
"Film": "The Fellowship Of The Ring",
"Chapter": "05: A Long Expected Party",
"Character": "Bilbo",
"Race": "Hobbit",
"Words": 326
},
I've tried to use the built-in dc tools to pluck and display this data accordingly however this as mentioned above inflates my data. I'm pretty sure I need to loop around the data set using a for loop but so far all I can come up with is the basic statement:
function show_race_data(ndx) {
var dim = ndx.dimension(dc.pluck('Race'));
var group = dim.group();
dc.pieChart('#race-graph')
.height(550)
.width(300)
.radius(90)
.transitionDuration(1500)
.dimension(race_dim)
.group(total_chars_per_race);
}
I think I need to group the characters like this:
var group = dim.group(character)
then for the loop:
let character = function(d.character) {
if (character <= 0;)
character ++;
} else if (character >= 1;)
character --;
}
I expect my output to properly display the data I'm after without the inflation.
I think I'd approach it like this (off the top of my head & untested demo below).
We'll count the occurrences of each character, adding them and removing them from an object (could be a Map if you're feeling ES6ish).
var dim = ndx.dimension(dc.pluck('Race'));
var raceCharGroup = dim.group().reduce(
function(p, v) { // add
p[v.Character] = (p[v.Character] || 0) + 1;
return p;
},
function(p, v) { // remove
if(--p[v.Character] === 0)
delete p[v.Character];
return p;
},
function() { // init
return {};
});
When we see a new character, we start that new entry at 0. When we decrement the count and it goes to 0, we remove the entry.
Well great, but now we have an object instead of a number of characters. But we can change the way a pie chart interprets these objects, to just count the number of keys:
pie.valueAccessor(function(kv) {
return Object.keys(kv.value).length;
})
I'm sure there are other ways to do this, but this is nice because it uses idiomatic group.reduce.