Underscore reporting
by SpAm
JavaScript
var meta = {};
var crosstab = [];
var data = [
{ sex:'Male', handed:'Right'},
{ sex:'Male', handed:'Left'},
{ sex:'Female', handed:'Right'},
{ sex:'Male', handed:'Right'},
];
function uniqueAttributeValue(rawData, attributeName) {
// use pluck to get all values for attributeName
var allValues = _.pluck(rawData, attributeName);
// create a unique list of the plucked values
var tmp = _.uniq(allValues);
// sort the values
var s = tmp.sort();
// add the uniqued values to the meta variable for later use
meta[attributeName] = s;
}
function createCrosstab(rawData) {
// loop through each handed
for (i = 0; i < meta.handed.length; i++) {
// loop through each sex
for (j = 0; j < meta.sex.length; j++) {
// create an empty row
var row = {};
// use map to find each combination of handed and sex
var x = _.map(rawData, function(d) {
if (d.sex == meta.sex[j] && d.handed == meta.handed[i]) {
return d.amount
} else {
return 0
}
});
// use reduce to summarize the amount value for each combination of handed and sex
var y = _.reduce(x, function(memo, num) {
return parseInt(memo) + parseInt(num)
});
// create a row for the crosstab
row = {
handed: meta.handed[i],
sex: meta.sex[j],
total: y
};
//push the row into the crosstab
crosstab.push(row);
}
}
console.log(crosstab);
}
// get the unique values of city
uniqueAttributeValue(data, 'sex');
//get the unique values of year
uniqueAttributeValue(data, 'handed');
console.log(meta);
data = _.map(data, function(i, v){
i.amount = 1;
return i;
});
// create crosstab of amounts by year and city
createCrosstab(data);
//var f = _.groupByMulti(data,...