javascript - What's a more effective or shorter way to group, then get a percentage value of a 2-dimensional array using underscore? -


i'm new using underscore i'm sure there better way following:

var data = [     {"from": "belgium", "to": "belgium", "count": "0"},     {"from": "belgium", "to": "france",  "count": "3"},     {"from": "belgium", "to": "germany", "count": "5"},     {"from": "france",  "to": "belgium", "count": "4"},     {"from": "france",  "to": "france",  "count": "9"},     {"from": "france",  "to": "germany", "count": "1"},     {"from": "germany", "to": "belgium", "count": "7"},     {"from": "germany", "to": "france",  "count": "2"},     {"from": "germany", "to": "germany", "count": "5"}, ] 

to

var formatted_data = [     [0, 0.08333333333, 0.13888888888],      [0.11111111111, 0.25, 0.02777777777],     [0.19444444444, 0.05555555555, 0.13888888888] ] 

basically group "from", divide each count total (in case 36). don't want hardcode number of countries, data include every combination of "from" , "to".

this code (but know can better):

var total = _.pluck(data, "count").reduce(function(memo, value) { return memo + parseint(value, 10); }, 0);  data = _.groupby(data, function(value) { return value.from; });  formatted_data = [];  _.each(data, function(value, key, list) {     formatted_data.push(_.pluck(data[key], "count").map(function(value) { return value/total; })); }); 

this solution simplifies total calculation , grouping country:

var total = _.reduce(data, function(memo, value){     return memo + parseint(value.count, 10); }, 0);  var counts = _.chain(data)     .groupby('from')     .map( function(country){         return _.map(country, function(value){             return parseint(value.count,10) / total;         });     })     .value(); 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -