简体   繁体   中英

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 to using underscore so I'm sure there is a better way to do the 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 you group it by "from", then divide each count by the total (in this case 36). I don't really want to hardcode the number of countries, but the data will always include every combination of "from" and "to".

This is my code (but I know it can probably be much 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; }));
});

How about this? (assumed that you already computed the value of total .)

var formatted_data = _(data).map(function (e) {
  return {from: e.from, v: parseInt(e.count,10)/total}; 
}).groupBy(function(e) {
  return e.from;
}).values().map(function (a) {
  return _.pluck(a, 'v');
}).value();

This solution simplifies the total calculation and the grouping by 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM